-
Notifications
You must be signed in to change notification settings - Fork 34
/
console_ui.dart
1696 lines (1422 loc) · 68.6 KB
/
console_ui.dart
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
import 'dart:io';
import 'dart:convert';
import 'package:nostr_console/event_ds.dart';
import 'package:nostr_console/tree_ds.dart';
import 'package:nostr_console/relays.dart';
import 'package:nostr_console/settings.dart';
import 'package:nostr_console/utils.dart';
import 'package:nostr_console/user.dart';
import 'package:bip340/bip340.dart';
Future<void> processAnyIncomingEvents(Store node, [bool printNotifications = true]) async {
//print("In process incoming");
reAdjustAlignment();
const int waitMilliSeconds1 = 100, waitMilliSeconds2 = 200;
Future<void> foo1() async {
await Future.delayed(Duration(milliseconds: waitMilliSeconds1));
return;
}
await foo1();
// need a bit of wait to give other events to execute, so do a delay, which allows
// relays to recieve and handle new events
Future.delayed(const Duration(milliseconds: waitMilliSeconds2 ), () {
Set<String> newEventIds = node.processIncomingEvent(getRecievedEvents());
clearEvents();
List<int> numPrinted1 = [0,0,0];
if( printNotifications) {
// print all the new trees, the ones that we want to print
print("");
numPrinted1 = node.printTreeNotifications(newEventIds);
// need to clear because only top 20 events in each thread are printed or cleared with above
int clearNotifications (Tree t) => t.treeSelector_clearNotifications();
node.traverseStoreTrees(clearNotifications);
// print direc room notifications if any, and print summary of all notifications printed
directRoomNotifications(node, numPrinted1[0], numPrinted1[2]);
}
});
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: waitMilliSeconds2));
return;
}
await foo();
}
String mySign(String privateKey, String msg) {
String randomSeed = getRandomPrivKey();
randomSeed = randomSeed.substring(0, 32);
return sign(privateKey, msg, randomSeed);
}
Future<void> mySleep(int duration) async {
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: duration));
return;
}
await foo();
}
/* @function sendReplyPostLike Used to send Reply, Post and Like ( event 1 for reply and post, and event 7 for like/reaction)
* If replyToId is blank, then it does not reference any e/p tags, and thus becomes a top post
* otherwise e and p tags are found for the given event being replied to, if that event data is available
*/
Future<void> sendReplyPostLike(Store node, String replyToId, String replyKind, String content) async {
content = addEscapeChars(content);
String strTags = node.getTagStr(replyToId, exename, true, getTagsFromContent(content));
if( replyToId.isNotEmpty && strTags == "") { // this returns empty only when the given replyto ID is non-empty, but its not found ( nor is it 64 bytes)
print("${gWarningColor}The given target id was not found and/or is not a valid id. Not sending the event.$gColorEndMarker");
return;
}
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String id = getShaId(userPublicKey, createdAt.toString(), replyKind, strTags, content);
// generate POW if required
String vanityTag = strTags;
if (replyKind == "1" && gDifficulty > 0) {
if( gDebug > 0) log.info("Starting pow");
int numBytes = (gDifficulty % 4 == 0)? gDifficulty ~/ 4: gDifficulty ~/ 4 + 1;
String zeroString = "";
for( int i = 0; i < numBytes; i++) {
zeroString += "0";
}
int numShaDone = 0;
for( numShaDone = 0; numShaDone < 100000000; numShaDone++) {
vanityTag = strTags + ',["nonce","$numShaDone","$gDifficulty"]';
id = getShaId(userPublicKey, createdAt.toString(), replyKind, vanityTag, content);
if( id.substring(0, numBytes) == zeroString) {
break;
}
}
await mySleep(500);
if( gDebug > 0) log.info("Ending pow numShaDone = $numShaDone id = $id");
}
String sig = mySign(userPrivateKey, id);
String toSendMessage = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":$replyKind,"tags":[$vanityTag],"content":"$content","sig":"$sig"}]';
//print("sending $toSendMessage");
sendRequest( gListRelayUrls1, toSendMessage);
await mySleep(200);
}
// Sends a public channel message
Future<void> sendChannelMessage(Store node, Channel channel, String messageToSend, String replyKind) async {
messageToSend = addEscapeChars(messageToSend);
String strTags = node.getTagStrForChannel(channel, exename);
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String id = getShaId(userPublicKey, createdAt.toString(), replyKind, strTags, messageToSend);
String sig = mySign(userPrivateKey, id);
String toSendMessage = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":$replyKind,"tags":[$strTags],"content":"$messageToSend","sig":"$sig"}]';
//printInColor(toSendMessage, gCommentColor);
sendRequest( gListRelayUrls1, toSendMessage);
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: 300));
return;
}
await foo();
}
// Sends a public channel message
Future<void> sendChannelReply(Store node, Channel channel, String replyTo, String messageToSend, String replyKind) async {
messageToSend = addEscapeChars(messageToSend);
String strTags = node.getTagStrForChannelReply(channel, replyTo, exename);
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String id = getShaId(userPublicKey, createdAt.toString(), replyKind, strTags, messageToSend);
String sig = mySign(userPrivateKey, id);
String toSendMessage = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":$replyKind,"tags":[$strTags],"content":"$messageToSend","sig":"$sig"}]';
//printInColor(toSendMessage, gCommentColor);
sendRequest( gListRelayUrls1, toSendMessage);
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: 300));
return;
}
await foo();
}
// send DM
Future<void> sendDirectMessage(Store node, String otherPubkey, String messageToSend, {String replyKind = "4"}) async {
//messageToSend = addEscapeChars(messageToSend); since this get encrypted , it does not need escaping
String otherPubkey02 = "02" + otherPubkey;
String encryptedMessageToSend = myEncrypt(userPrivateKey, otherPubkey02, messageToSend);
//print("in sendDirectMessage: replyKind = $replyKind");
//String replyKind = "4";
String strTags = '["p","$otherPubkey"]';
strTags += gWhetherToSendClientTag?',["client","nostr_console"]':'';
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String id = getShaId(userPublicKey, createdAt.toString(), replyKind, strTags, encryptedMessageToSend);
String sig = mySign(userPrivateKey, id);
String eventStrToSend = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":$replyKind,"tags":[$strTags],"content":"$encryptedMessageToSend","sig":"$sig"}]';
//print("calling send for str : $eventStrToSend");
sendRequest( gListRelayUrls1, eventStrToSend);
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: 300));
return;
}
await foo();
}
// sends event e; used to send kind 3 event; can send other kinds too like channel create kind 40, or kind 0
// does not honor tags mentioned in the Event, excpet if its kind 3, when it uses contact list to create tags
Future<String> sendEvent(Store node, Event e, [int delayAfterSend = 500]) async {
String strTags = "";
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String content = addEscapeChars( e.eventData.content);
// read the contacts and make them part of the tags, and then the sha
if( e.eventData.kind == 3) {
strTags = ""; // only new contacts will be sent
for(int i = 0; i < e.eventData.contactList.length; i++) {
String relay = e.eventData.contactList[i].relay;
if( relay == "") {
relay = defaultServerUrl;
}
String comma = ",";
if( i == e.eventData.contactList.length - 1) {
comma = "";
}
String strContact = '["p","${e.eventData.contactList[i].contactPubkey}","$relay"]$comma';
strTags += strContact;
}
// strTags += '["client","nostr_console"]';
} else {
strTags += '["client","nostr_console"]';
}
String id = getShaId(userPublicKey, createdAt.toString(), e.eventData.kind.toString(), strTags, content);
String sig = mySign(userPrivateKey, id);
String toSendMessage = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":${e.eventData.kind.toString()},"tags":[$strTags],"content":"$content","sig":"$sig"}]';
//print("in send event: calling sendrequest for string \n $toSendMessage");
sendRequest(gListRelayUrls1, toSendMessage);
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: delayAfterSend));
return;
}
await foo();
return id;
}
Future<String> sendEventWithTags(Store node, Event e, String tags) async {
String strTags = tags;
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String content = addEscapeChars( e.eventData.content);
String id = getShaId(userPublicKey, createdAt.toString(), e.eventData.kind.toString(), strTags, content);
String sig = mySign(userPrivateKey, id);
String toSendMessage = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":${e.eventData.kind.toString()},"tags":[$strTags],"content":"$content","sig":"$sig"}]';
//print("in send event: calling sendrequest for string \n $toSendMessage");
sendRequest(gListRelayUrls1, toSendMessage);
Future<void> foo() async {
await Future.delayed(Duration(milliseconds: 500));
return;
}
await foo();
return id;
}
bool sendDeleteEvent(Store node, String eventIdToDelete) {
if( node.allChildEventsMap.containsKey(eventIdToDelete)) {
Tree? tree = node.allChildEventsMap[eventIdToDelete];
if( tree != null) {
if( tree.event.eventData.id == eventIdToDelete && tree.event.eventData.pubkey == userPublicKey) {
// to delte this event
String replyKind = "5"; // delete event
String content = "";
String strTags = '["e","$eventIdToDelete"]';
strTags += gWhetherToSendClientTag?',["client","nostr_console"]':'';
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
String id = getShaId(userPublicKey, createdAt.toString(), replyKind, strTags, content);
String sig = mySign(userPrivateKey, id);
String toSendMessage = '["EVENT",{"id":"$id","pubkey":"$userPublicKey","created_at":$createdAt,"kind":$replyKind,"tags":[$strTags],"content":"$content","sig":"$sig"}]';
sendRequest( gListRelayUrls1, toSendMessage);
print("sent event delete request with id = $id");
} else {
print("${gWarningColor}The given id was not found and/or is not a valid id, or is not your event. Not deleted.$gColorEndMarker");
}
} else {
print("Event not found. Kindly ensure you have entered a valid event id.");
}
};
return false;
}
void reAdjustAlignment() {
// align the text again in case the window size has been changed
if( gAlignment == "center") {
try {
var terminalColumns = gDefaultTextWidth;
if( stdout.hasTerminal )
terminalColumns = stdout.terminalColumns;
if( gTextWidth > terminalColumns) {
gTextWidth = terminalColumns - 5;
}
gNumLeftMarginSpaces = (terminalColumns - gTextWidth )~/2;
} on StdoutException catch (e) {
print("Terminal information not available");
if( gDebug>0) print("${e.message}");
gNumLeftMarginSpaces = 0;
}
}
Store.reCalculateMarkerStr();
}
void printProfile(Store node, String profilePubkey) {
bool onlyUserPostAndLike (Tree t) => t.treeSelectorUserPostAndLike({profilePubkey});
node.printStoreTrees(0, DateTime.now().subtract(Duration(hours:gHoursDefaultPrint)), onlyUserPostAndLike);
// if contact list was found, get user's feed, and keep the contact list for later use
String authorName = getAuthorName(profilePubkey);
String pronoun = "";
if( profilePubkey == userPublicKey) {
printUnderlined("\nYour profile - $authorName:");
pronoun = "You";
} else {
printUnderlined("\nProfile for $authorName");
pronoun = "They";
}
String about = gKindONames[profilePubkey]?.about??"";
String picture = gKindONames[profilePubkey]?.picture??"";
String lud06 = gKindONames[profilePubkey]?.lud06??"";
String lud16 = gKindONames[profilePubkey]?.lud16??"";
String display_name= gKindONames[profilePubkey]?.display_name??"";
String website = gKindONames[profilePubkey]?.website??"";
int dateLastUpdated = gKindONames[profilePubkey]?.createdAt??0;
bool verified = gKindONames[profilePubkey]?.nip05Verified??false;
String nip05Id = gKindONames[profilePubkey]?.nip05Id??"";
// print QR code
print("The QR code for public key:\n\n");
try {
print(getPubkeyAsQrString(profilePubkey));
} catch(e) {
print("Could not generate qr code. \n");
}
// print LNRUL lud06 if it exists
if( lud06.length > gMinLud06AddressLength) {
try {
String lud06LNString = "lightning:" + lud06;
List<int>? typesAndModule = getTypeAndModule(lud06LNString);
if( typesAndModule != null) {
print("Printing lud06 LNURL as QR:\n\n");
print(getPubkeyAsQrString(lud06LNString, typesAndModule[0], typesAndModule[1]));
}
} catch(e) {
print("Could not generate qr code for the lnurl given. \n");
}
}
// print LNRUL lud16 if it exists
if( lud16.length > gMinLud16AddressLength) {
try {
String lud16LNString = "" + lud16;
List<int>? typesAndModule = getTypeAndModule(lud16LNString);
if( typesAndModule != null) {
print("Printing lud16 address as QR:\n\n");
print(getPubkeyAsQrString(lud16LNString, typesAndModule[0], typesAndModule[1]));
}
} catch(e) {
print("Could not generate qr code for the given address.\n");
}
}
print("\nName : $authorName ( ${profilePubkey} ).");
print("About : $about");
print("Picture : $picture");
print("display_name: $display_name");
print("Website : $website");
print("Lud06 : $lud06");
print("Lud16 : $lud16");
print("Nip 05 : ${verified?"yes. ${nip05Id}":"no"}");
print("\nLast Updated: ${getPrintableDate(dateLastUpdated)}\n");
// get the latest kind 3 event for the user, which lists his 'follows' list
Event? profileContactEvent = getContactEvent(profilePubkey);
if (profileContactEvent != null ) {
if( profilePubkey != userPublicKey) {
if( profileContactEvent.eventData.contactList.any((x) => (x.contactPubkey == userPublicKey))) {
print("* They follow you");
} else {
print("* They don't follow you");
}
}
// print mutual follows
node.printMutualFollows(profileContactEvent, authorName);
print("");
// print follow list
stdout.write("$pronoun follow ${profileContactEvent.eventData.contactList.length} accounts: ");
profileContactEvent.eventData.contactList.sort();
profileContactEvent.eventData.contactList.forEach((x) => stdout.write("${getAuthorName(x.contactPubkey)}, "));
print("\n");
}
// print followers
List<String> followers = node.getFollowers(profilePubkey);
stdout.write("$pronoun have ${followers.length} followers: ");
followers.sort((a, b) => getAuthorName(a).compareTo(getAuthorName(b)));
followers.forEach((x) => stdout.write("${getAuthorName(x)}, "));
print("");
print("");
}
void printVerifiedAccounts(Store node) {
List<dynamic> listVerified = []; // num follows, pubkey, name, nip05id
printUnderlined("NIP 05 Verified Users");
print("") ;
print("Username Num Followers pubkey Nip Id\n");
gKindONames.forEach((key, value) {
String pubkey = key;
if( value.nip05Verified) {
List<String> followers = node.getFollowers(pubkey);
listVerified.add([followers.length, pubkey, getAuthorName(pubkey), value.nip05Id]);
}
});
listVerified.sort((a, b) => a[0] > b[0]? -1: (a[0] == b[0]? 0: 1));
for(var verifiedEntry in listVerified) {
print("${verifiedEntry[2].padRight(30)} ${verifiedEntry[0].toString().padRight(4)} ${verifiedEntry[1]} ${verifiedEntry[3]}");
}
print("\nHow to use: To get best results, print the main feed a couple of times right after starting; and then check NIP verified list. This gives application time to do the verification from user's given servers.\n\n");
}
void printMenu(List<String> menuOptions) {
int longestMenuOption = 0;
for(int i = 0; i < menuOptions.length;i++) {
if( longestMenuOption < menuOptions[i].length) {
longestMenuOption = menuOptions[i].length;
}
}
var terminalColumns = gDefaultTextWidth;
if( stdout.hasTerminal )
terminalColumns = stdout.terminalColumns;
if( longestMenuOption + 5> gMenuWidth )
gMenuWidth = longestMenuOption + 8;
if( terminalColumns~/gMenuWidth > 4) {
terminalColumns = gMenuWidth * 4;
}
int rowLen = 0;
for(int i = 0; i < menuOptions.length;i++) {
String str = "${i+1}. ${menuOptions[i]}";
str = str.padRight(gMenuWidth);
stdout.write(str);
rowLen += gMenuWidth;
if( rowLen + gMenuWidth> terminalColumns ) {
stdout.write("\n" );
rowLen = 0;
}
}
stdout.write("\n" );
}
int showMenu(List<String> menuOptions, String menuName, [String menuInfo = ""]) {
if(menuInfo.length > 0) {
print("\n$menuInfo\n");
}
while(true) {
printInColor(" $menuName", yellowColor);
print("\n");
printMenu(menuOptions);
String promptWithName = userPrivateKey.length == 64?
"Signed in as $gCommentColor${getAuthorName(userPublicKey)}$gColorEndMarker":
"${gWarningColor}You are not signed in so can't send any messages$gColorEndMarker";
stdout.write("$promptWithName. ");
stdout.write("Type option number: ");
String? userOptionInput = stdin.readLineSync();
String userOption = userOptionInput??"";
userOption = userOption.trim();
if( userOption == 'x') {
userOption = menuOptions.length.toString();
}
if( int.tryParse(userOption) != null) {
try{
int? valueOption = int.tryParse(userOption);
if( valueOption != null) {
if( valueOption >= 1 && valueOption <= menuOptions.length) {
reAdjustAlignment(); // in case user has changed alignment
print('You picked: $valueOption');
// reset this
gInvalidInputCount = 0;
return valueOption;
}
}
} on FormatException catch (e) {
print(e.message);
} on Exception catch (e) {
print(e);
}
}
printWarning("\nInvalid option. Kindly try again. The valid options are from 1 to ${menuOptions.length}");
gInvalidInputCount++;
if( gInvalidInputCount > gMaxInValidInputAccepted) {
printWarning("The program has received an invalid input more than $gMaxInValidInputAccepted. There seems to be some problem etc, so exiting");
exit(0);
//programExit();
}
}
}
bool confirmFirstContact() {
String s = getStringFromUser(
"""\nIt appears your contact list is empty.
If you are a new user, you should proceed, but if you already
had added people in past, then that contact list would be overwritten.
Do you want to proceed. Press y/Y or n/N: """, "n");
if( s == 'y' || s == 'Y') {
return true;
}
return false;
}
void printPubkeys(Set<String> pubkey) {
print("${myPadRight("pubkey",64)} ${myPadRight("name", 20)} ${myPadRight("about", 40)} ${myPadRight("Nip05", 30)}");
pubkey.forEach( (x) => print("$x ${myPadRight(getAuthorName(x), 20)} ${myPadRight(gKindONames[x]?.about??"", 40)} ${myPadRight(gKindONames[x]?.nip05Id??"No", 30)}"));
print("");
}
void printPubkeyResult(Set<String> pubkey) {
if( pubkey.length == 0) {
print("There is no pubkey for that given name.");
return;
} else {
if( pubkey.length == 1) {
print("There is 1 public key for the given name, which is: ");
} else {
print("There are ${pubkey.length} public keys for the given name, which are: ");
}
}
printPubkeys(pubkey);
}
Future<void> otherOptionsMenuUi(Store node) async {
bool continueOtherMenu = true;
while(continueOtherMenu) {
await processAnyIncomingEvents(node); // this takes 300 ms
int option = showMenu([
'Search by client name', // 1
'Edit your profile', // 2
'Delete event', // 3
'Re-Broadcast contact list+', // 4
'Application stats', // 5
'Help and About', // 6
'E(x)it to main menu'], // 7
"Other Options Menu"); // menu name
switch(option) {
case 1:
stdout.write("Enter nostr client name whose events you want to see: ");
String? $tempWords = stdin.readLineSync();
String clientName = $tempWords??"";
if( clientName != "") {
bool fromClient (Tree t) => t.treeSelectorClientName(clientName);
node.printStoreTrees(0, DateTime.now().subtract(Duration(hours:gHoursDefaultPrint)), fromClient); // search for last gHoursDefaultPrint hours only
}
break;
case 2: //edit your profile
if( userPublicKey == "" || userPrivateKey == "") {
printWarning("No private key provided so you can't edit your profile.");
break;
}
print("Your current name: ${getAuthorName(userPublicKey)}");
print("Your 'about me': ${gKindONames[userPublicKey]?.about}");
print("Your current profile picture: ${gKindONames[userPublicKey]?.picture}");
print("Your current display name: ${gKindONames[userPublicKey]?.display_name}");
print("Your current website: ${gKindONames[userPublicKey]?.website}");
print("Your current NIP 05 id: ${gKindONames[userPublicKey]?.nip05Id}");
print("Your current lud06: ${gKindONames[userPublicKey]?.lud06}");
print("Your current lud16: ${gKindONames[userPublicKey]?.lud16}");
print("\n\nEnter new data. Leave blank to use the old value. Some clients use name, others use display name; you can enter same value for both:\n");
String userName = getStringFromUser("Enter your new name : ", getAuthorName(userPublicKey));
String userAbout = getStringFromUser("Enter new 'about me' for yourself : ", gKindONames[userPublicKey]?.about??"");
String userPic = getStringFromUser("Enter url to your new display picture: ", gKindONames[userPublicKey]?.picture??"https://placekitten.com/200/200");
String display_name = getStringFromUser("Enter your new display name : ", gKindONames[userPublicKey]?.display_name??"");
String website = getStringFromUser("Enter your new website : ", gKindONames[userPublicKey]?.website??"");
String nip05id = getStringFromUser("Enter your nip 05 id. Leave blank if unknown/none: ", gKindONames[userPublicKey]?.nip05Id??"");
String lud06 = getStringFromUser("Enter your lud06 or lnurl. Leave blank if unknown/none: ", gKindONames[userPublicKey]?.lud06??"");
String lud16 = getStringFromUser("Enter your lud16 address. Leave blank if unknown/none: ", gKindONames[userPublicKey]?.lud16??"");
String strLud06 = lud06.length > 0? '"lud06":"$lud06",': '';
String strLud16 = lud16.length > 0? '"lud16":"$lud16",': '';
String strDispName = display_name.length > 0? '"display_name":"$display_name",': '';
String strWebsite = website.length > 0? '"website":"$website",': '';
String content = "{\"name\": \"$userName\", \"about\": \"$userAbout\", \"picture\": \"$userPic\"${ nip05id.length >0 ? ", $strDispName $strWebsite $strLud06 $strLud16 \"nip05\": \"$nip05id\"":""}}";
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
EventData eventData = EventData('id', userPublicKey, createdAt, 0, content, [], [], [], [], {}, );
Event userKind0Event = Event("EVENT", "id", eventData, [], "");
String userKind0EventId = await sendEvent(node, userKind0Event); // takes 400 ms
printInColor("Updated your profile.\n", gCommentColor);
await processAnyIncomingEvents(node, false); // get latest event, this takes 300 ms
break;
case 3:
if( userPublicKey == "" || userPrivateKey == "") {
printWarning("No private key provided so you can't delete any event.");
break;
}
stdout.write("Enter event id to delete: ");
String? $tempEventId = stdin.readLineSync();
String userInputId = $tempEventId??"";
Set<String> eventIdToDelete = node.getEventEidFromPrefix(userInputId);
if( eventIdToDelete.length == 1) {
String toDeleteId = eventIdToDelete.first;
print("Going to send a delete event for the following event with id ${toDeleteId}");
sendDeleteEvent(node, eventIdToDelete.first);
await processAnyIncomingEvents(node, false); // get latest event, this takes 300 ms
} else {
if( eventIdToDelete.length == 0) {
printWarning("Could not find the given event id. Kindly try again, by entering a 64 byte long hex event id, or by entering a unique prefix for the given event id.");
} else {
printWarning("Invalid Event Id(s). Kindly enter a more unique id.");
}
}
break;
case 4:
print("TODO");
break;
printSet(gListRelayUrls1, "Going to broadcast your contact list ( kind 3) and About me( kind 0) to all relays. The relays are: ", ",");
stdout.write("Hold on, sending events to relays ...");
int count = 0;
Set<int> kindBroadcast = {};
node.allChildEventsMap.forEach((id, tree) {
if( tree.event.eventData.pubkey == userPublicKey && [0,3].contains(tree.event.eventData.kind)) {
sendEvent(node, tree.event, 100);
count++;
}
});
stdout.write("..done\n");
print("\nFinished re-broadcasting $count events to all the servers.");
break;
case 5: // application info
print("\n\n");
printUnderlined("Application stats");
//print("\n");
relays.printInfo();
print("\n");
printUnderlined("Event and User Info");
//print("Total number of kind-1 posts: ${node.count()}");
print("\nEvent distribution by event kind:\n");
node.printEventInfo();
print("\nTotal number of all events: ${node.allChildEventsMap.length}");
print("\nTotal events translated for $gNumTranslateDays days: $numEventsTranslated");
print("Total number of user profiles: ${gKindONames.length}\n");
printUnderlined("Logged in user Info");
if( userPrivateKey.length == 64) {
print("You are signed in, and your public key is: $userPublicKey");
} else {
print("You are not signed in, and are using public key: $userPublicKey");
}
print("Your name as seen in metadata event is: ${getAuthorName(userPublicKey)}\n");
printVerifiedAccounts(node);
break;
case 6:
print(helpAndAbout);
break;
case 7:
continueOtherMenu = false;
break;
default:
break;
}
}
return;
}
// sends event creating a new public channel
Future<void> createPublicChannel(Store node) async {
String channelName = getStringFromUser("Enter channel name: ");
String channelAbout = getStringFromUser("Enter description for channel: ");
String channelPic = getStringFromUser("Enter display picture if any: ", "https://placekitten.com/200/200");
String content = "{\"name\": \"$channelName\", \"about\": \"$channelAbout\", \"picture\": \"$channelPic\"}";
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
EventData eventData = EventData('id', userPublicKey, createdAt, 40, content, [], [], [], [], {}, );
Event channelCreateEvent = Event("EVENT", "id", eventData, [], "");
String newChannelId = await sendEvent(node, channelCreateEvent); // takes 400 ms
print("Created new channel with id: $newChannelId");
await processAnyIncomingEvents(node, false); // get latest event, this takes 300 ms
}
Future<void> channelMenuUI(Store node) async {
bool continueChatMenu = true;
bool justShowedChannels = false;
while(continueChatMenu) {
await processAnyIncomingEvents(node); // this takes 300 ms
if( !justShowedChannels) {
printInColor(" Public Channels ", gCommentColor);
node.printChannelsOverview(node.channels, gNumRoomsShownByDefault, selectorShowAllRooms, node.allChildEventsMap, null);
justShowedChannels = true;
}
String menuInfo = """Public channel howto: To enter a channel, enter first few letters of its name or the channel identifier.
When inside a channel, the first column is the id of the given post. It can be used when you want to reply to a specific post.
To reply to a specific post, type '/reply <first few letters of id of post to reply to> <your message>.
When in a channel, press 'x' to exit. """;
int option = showMenu([ 'Enter a public channel', // 1
'Show all public channels', // 2
'Create channel', // 3
'E(x)it to main menu'], // 4
"Public Channels Menu", // name of menu
menuInfo);
switch(option) {
case 1:
justShowedChannels = false;
bool showChannelOption = true;
stdout.write("\nType channel id or name, or their 1st few letters; or type 'x' to go to menu: ");
String? $tempUserInput = stdin.readLineSync();
String channelId = $tempUserInput??"";
if( channelId == "x") {
showChannelOption = false;
clearScreen();
}
int pageNum = 1;
bool firstIteration = true;
while(showChannelOption) {
reAdjustAlignment();
if( firstIteration) {
clearScreen();
firstIteration = false;
}
String fullChannelId = node.showChannel(node.channels, channelId, null, null, null, pageNum); // direct channel does not need this, only encrypted channels needs them
if( fullChannelId == "") {
//print("Could not find the given channel.");
showChannelOption = false;
break;
}
stdout.write("\nType message; or type 'x' to exit, or press <enter> to refresh: ");
$tempUserInput = stdin.readLineSync(encoding: utf8);
String messageToSend = $tempUserInput??"";
print("got word: $messageToSend");
if( messageToSend != "") {
if( messageToSend == 'x') {
showChannelOption = false;
} else {
int retval = 0;
if( (retval = messageToSend.isChannelPageNumber(gMaxChannelPagesDisplayed)) != 0 ) {
print('is channel page number: $retval');
pageNum = retval;
} else {
// in case the program was invoked with --pubkey, then user can't send messages
if( userPrivateKey == "") {
printWarning("Since no user private key has been supplied, posts/messages can't be sent. Invoke with --prikey \n");
} else {
if( messageToSend.length >= 7 && messageToSend.substring(0, 7).compareTo("/reply ") == 0) {
List<String> tokens = messageToSend.split(' ');
if( tokens.length >= 3) {
String replyTo = tokens[1];
Channel? channel = node.getChannelFromId(node.channels, fullChannelId);
String actualMessage = messageToSend.substring(7);
if( messageToSend.indexOf(tokens[1]) + tokens[1].length < messageToSend.length)
actualMessage = messageToSend.substring( messageToSend.indexOf(tokens[1]) + tokens[1].length + 1);
if( channel != null) {
await sendChannelReply(node, channel, replyTo, actualMessage, getPostKindFrom( channel.roomType));
pageNum = 1; // reset it
}
}
} else {
// send message to the given room
Channel? channel = node.getChannelFromId(node.channels, fullChannelId);
if( channel != null) {
await sendChannelMessage(node, channel, messageToSend, getPostKindFrom(channel.roomType));
pageNum = 1; // reset it
}
}
}
}
}
} else {
print("Refreshing...");
}
clearScreen();
await processAnyIncomingEvents(node, false);
} // end while showChannelOption
break;
case 2:
clearScreen();
printInColor(" All Public Channels ", gCommentColor);
node.printChannelsOverview(node.channels, node.channels.length, selectorShowAllRooms, node.allChildEventsMap, null);
justShowedChannels = true;
break;
case 3:
clearScreen();
if( userPrivateKey == "") {
printWarning("Since no user private key has been supplied, you cannot create channels or send any event. Invoke with --prikey \n");
justShowedChannels = false;
break;
}
print("Creating new channel. Kindly enter info about channel: \n");
await createPublicChannel(node);
clearScreen();
justShowedChannels = false;
// TODO put user in the newly created channel
break;
case 4:
continueChatMenu = false;
break;
default:
break;
}
}
return;
}
// sends event creating a new public channel
Future<void> createEncryptedChannel(Store node) async {
String channelName = getStringFromUser("Enter encrypted channel name: ");
String channelAbout = getStringFromUser("Enter description for the new encrypted channel: ");
String channelPic = getStringFromUser("Enter display picture if any: ", "https://placekitten.com/200/200");
String content = "{\"name\": \"$channelName\", \"about\": \"$channelAbout\", \"picture\": \"$channelPic\"}";
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
List<String> participants = [userPublicKey];
String pTags = '';
for( int i = 0; i < participants.length; i++) {
if( i > 0) {
pTags += ",";
}
pTags += '["p","${participants[i]}"]';
}
EventData eventData = EventData('id', userPublicKey, createdAt, 140, content, [], [], [], [], {}, );
Event encryptedChannelCreateEvent = Event("EVENT", "id", eventData, [], "");
String newEncryptedChannelId = await sendEventWithTags(node, encryptedChannelCreateEvent, pTags); // takes 400 ms
clearScreen();
print("Created new encrypted channel with id: $newEncryptedChannelId\n");
String newPriKey = getRandomPrivKey();
// Created and going to use new random privake key
String channelPriKey = newPriKey, channelPubKey = myGetPublicKey(newPriKey);
// now send password as direct message to yourself and to all the people you tagged
String messageToSend = "App Encrypted Channels: inviting you to encrypted channel $newEncryptedChannelId encrypted using private public keys $channelPriKey $channelPubKey";
for( int i = 0; i < participants.length; i++) {
// send message to all ( including self which is in that list)
await sendDirectMessage(node, participants[i], messageToSend, replyKind: gSecretMessageKind.toString());
}
await processAnyIncomingEvents(node, false); // get latest event, this takes 300 ms
}
// sends event creating a new public channel
Future<void> updateEncryptedChannel(Store node, String channelId,
String channelName, String channelAbout, String channelPic, String content, String tags,
Set<String> participants, Set<String> newParticipants) async {
List<String> keys = getEncryptedChannelKeys(node.encryptedGroupInviteIds, node.allChildEventsMap, channelId);
if( keys.length == 2) {
String channelPriKey = keys[0], channelPubKey = keys[1];
// now send password as direct message to yourself and to all the people you tagged
String messageToSend = "App Encrypted Channels: inviting you to encrypted channel $channelId encrypted using private public keys $channelPriKey $channelPubKey";
// send message to all new participants
newParticipants.forEach((participant) async {
await sendDirectMessage(node, participant, messageToSend, replyKind: gSecretMessageKind.toString());
});
int createdAt = DateTime.now().millisecondsSinceEpoch ~/1000;
EventData eventData = EventData('id', userPublicKey, createdAt, 141, content, [], [], [], [], {}, );
Event channelUpdateEvent = Event("EVENT", "id", eventData, [], "");
await sendEventWithTags(node, channelUpdateEvent, tags); // takes 400 ms
await processAnyIncomingEvents(node, false); // get latest event, this takes 300 ms
} else {
printWarning("Could not find shared-secret keys for the channel. Could not update.");
}
}
String encryptChannelMessage(Store node, String channelId, String messageToSend) {
String encryptedMessage = '';
List<String> keys = getEncryptedChannelKeys(node.encryptedGroupInviteIds, node.allChildEventsMap, channelId);
if( keys.length != 2) {
printWarning("Could not get channel secret for channel id: $channelId");
return '';
}
String priKey = keys[0], pubKey = keys[1];
encryptedMessage = myEncrypt(priKey, "02" + pubKey, messageToSend);
return encryptedMessage;
}
Future<void> addUsersToEncryptedChannel(Store node, String fullChannelId, Set<String> newPubKeys) async {
// first check user is creator of channel
Event? channelEvent = node.allChildEventsMap[fullChannelId]?.event;
if( channelEvent != null) {
if( channelEvent.eventData.pubkey == userPublicKey) {
Channel? channel = node.getChannelFromId(node.encryptedChannels, fullChannelId);
if( channel != null ) {
Set<String> newParticipants = {};
Set<String> participants = channel.participants;
int numOldUsers = participants.length;
// now send invite
List<String> toAdd = [];
for(var newPubkey in newPubKeys) {
if( newPubkey.length != 64) {
printWarning("Invalid pubkey. The given pubkey should be 64 byte long. offending pubkey: $newPubkey");
continue;
}
toAdd.add(newPubkey);
newParticipants.add(newPubkey);
participants.add(newPubkey);
}
String channelName = node.getChannelNameFromId(node.encryptedChannels, fullChannelId);
String channelAbout = "";
String channelPic = "https://placekitten.com/200/200";
String content = channelEvent.eventData.content;
String tags = '["e","$fullChannelId"]';
participants.forEach((participant) {
tags += ',["p","${participant}"]';
});
int numNewUsers = participants.length;
if( numNewUsers > numOldUsers) {
print("\nSending kind 141 invites to new participants: $newParticipants");
await updateEncryptedChannel(node, fullChannelId, channelName, channelAbout, channelPic, content, tags, participants, newParticipants);
} else {
printWarning("\nNote: No new users added. Kindly check whether the given user(s) aren't already members of the group, that pubkeys are valid etc");
}
}
} else {
printWarning("Not being the creator of this channel, you cannot add members to it.");
}
}
}
Future<void> sendInvitesForEncryptedChannel(Store node, String channelId, Set<String> newPubKeys) async {
// first check user is creator of channel
Event? channelEvent = node.allChildEventsMap[channelId]?.event;
if( channelEvent != null) {
if( channelEvent.eventData.pubkey == userPublicKey) {