-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path50_Signalbot.pm
executable file
·3076 lines (2876 loc) · 116 KB
/
50_Signalbot.pm
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
##############################################
#$Id$
my $Signalbot_VERSION="3.21";
# Simple Interface to Signal CLI running as Dbus service
# Author: Adimarantis
# License: GPL
# Credits to FHEM Forum Users Quantum (SiSi Module) and Johannes Viegener (Telegrambot Module) for code fragments and ideas
# Requires signal_cli (https://github.com/AsamK/signal-cli) and Protocol::DBus to work
# Verbose levels
# 5 = Internal data and function calls
# 4 = User actions and results
# 3 = Error messages
package main;
use strict;
use warnings;
use Scalar::Util qw(looks_like_number);
use File::Temp qw( tempfile tempdir );
use Text::ParseWords;
use Encode;
#use Data::Dumper;
use Time::HiRes qw( usleep );
use URI::Escape;
use HttpUtils;
use MIME::Base64;
eval "use Protocol::DBus;1";
eval "use Protocol::DBus::Client;1" or my $DBus_missing = "yes";
sub LogUnicode($$$);
require FHEM::Text::Unicode;
use FHEM::Text::Unicode qw(:ALL);
use vars qw(%FW_webArgs); # all arguments specified in the GET
use vars qw($FW_detail); # currently selected device for detail view
use vars qw($FW_RET);
use vars qw($FW_wname);
#maybe really get introspective here instead of handwritten list
my %signatures = (
"setContactBlocked" => "sb", #
"setGroupBlocked" => "ayb", # https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number___groupid__block
"updateGroup" => "aysass", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/put_v1_groups__number___groupid_
"updateProfile" => "ssssb", #https://bbernhard.github.io/signal-cli-rest-api/#/Profiles/put_v1_profiles__number_
"quitGroup" => "ay", #obselete - use new API
"joinGroup" => "s", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number___groupid__join
"sendGroupMessage" => "sasay",
"sendNoteToSelfMessage" => "sas",
"sendMessage" => "sasas", #https://bbernhard.github.io/signal-cli-rest-api/#/Messages/post_v2_send
"getContactName" => "s",
"setContactName" => "ss",
"getGroupIds" => "", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/get_v1_groups__number_
"getGroupName" => "ay",
"getGroupMembers" => "ay",#https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number___groupid__members
"listNumbers" => "", #??? https://bbernhard.github.io/signal-cli-rest-api/#/Accounts/get_v1_accounts
"getContactNumber" => "s",
"isContactBlocked" => "s",
"isGroupBlocked" => "ay",
"isMember" => "ay",
"createGroup" => "sass", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number_
"getSelfNumber" => "", #V0.9.1
"deleteContact" => "s", #V0.10.0
"deleteRecipient" => "s", #V0.10.0
"setPin" => "s", #V0.10.0
"removePin" => "", #V0.10.0
"getGroup" => "ay", #V0.10.0 #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/get_v1_groups__number___groupid_
"getIdentity" => "s", #V0.12.0
"addDevice" => "s",
"listDevices" => "",
"listIdentities" => "", #V0.12.0 #https://bbernhard.github.io/signal-cli-rest-api/#/Identities/get_v1_identities__number_
"unregister" => "", #https://bbernhard.github.io/signal-cli-rest-api/#/Devices/post_v1_unregister__number_
"sendEndSessionMessage" => "as", #unused
"sendRemoteDeleteMessage" => "xas", #unused
"sendGroupRemoteDeletemessage" => "xay",#unused
"sendMessageReaction" => "sbsxas", #unused
"sendGroupMessageReaction" => "sbsxay", #unused
"submitRateLimitChallenge" => "ss",
);
my %groupsignatures = (
#methods in the "Groups" object from V0.10
"deleteGroup" => "", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/delete_v1_groups__number___groupid_
"addMembers" => "as", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number___groupid__members
"removeMembers" => "as", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/delete_v1_groups__number___groupid__members
"quitGroup" => "", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number___groupid__quit
"addAdmins" => "as", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/post_v1_groups__number___groupid__admins
"removeAdmins" => "as", #https://bbernhard.github.io/signal-cli-rest-api/#/Groups/delete_v1_groups__number___groupid__admins
);
my %identitysignatures = (
#methods in the "Identities" object from V0.11.12
"trust" => "", #https://bbernhard.github.io/signal-cli-rest-api/#/Identities/put_v1_identities__number__trust__numberToTrust_
"trustVerified" => "s",
);
#dbus interfaces that only exist in registration mode
my %regsig = (
"listAccounts" => "", #https://bbernhard.github.io/signal-cli-rest-api/#/Accounts/get_v1_accounts
"link" => "s", #https://bbernhard.github.io/signal-cli-rest-api/#/Devices/get_v1_qrcodelink
"registerWithCaptcha" => "sbs", #Redundant to register
"verifyWithPin" => "sss", #not used
"register" => "sb", #https://bbernhard.github.io/signal-cli-rest-api/#/Devices/post_v1_register__number_
"verify" => "ss", #https://bbernhard.github.io/signal-cli-rest-api/#/Devices/post_v1_register__number__verify__token_
"version" => "",
);
sub Signalbot_Initialize($) {
my ($hash) = @_;
$hash->{DefFn} = "Signalbot_Define";
$hash->{FW_detailFn} = "Signalbot_Detail";
$hash->{FW_deviceOverview} = 1;
$hash->{AttrFn} = "Signalbot_Attr";
$hash->{SetFn} = "Signalbot_Set";
$hash->{ReadFn} = "Signalbot_Read";
$hash->{NotifyFn} = 'Signalbot_Notify';
$hash->{StateFn} = "Signalbot_State";
$hash->{GetFn} = "Signalbot_Get";
$hash->{UndefFn} = "Signalbot_Undef";
$hash->{MessageReceived} = "Signalbot_MessageReceived";
$hash->{MessageReceivedV2} = "Signalbot_MessageReceivedV2";
$hash->{ReceiptReceived} = "Signalbot_ReceiptReceived";
$hash->{SyncMessageReceived} = "Signalbot_SyncMessageReceived";
$hash->{version} = "Signalbot_Version_cb";
$hash->{updateGroup} = "Signalbot_UpdateGroup_cb";
$hash->{createGroup} = "Signalbot_UpdateGroup_cb";
$hash->{joinGroup} = "Signalbot_UpdateGroup_cb";
$hash->{listNumbers} = "Signalbot_ListNumbers_cb";
$hash->{listIdentities} = "Signalbot_ListIdentities_cb";
$hash->{AttrList} = "IODev do_not_notify:1,0 ignore:1,0 showtime:1,0 ".
"defaultPeer: ".
"allowedPeer ".
"babblePeer ".
"babbleDev ".
"babbleExclude ".
"authTimeout ".
"authDev ".
"authTrusted:yes,no ".
"sendTimeout ".
"cmdKeyword ".
"cmdFavorite ".
"favorites:textField-long ".
"autoJoin:yes,no ".
"formatting:none,html,markdown,both ".
"registerMethod:SMS,Voice ".
"$readingFnAttributes";
$data{FWEXT}{"/Signalbot_sendMsg"}{CONTENTFUNC} = "Signalbot_sendMsg";
}
sub Signalbot_sendMsg($@) {
my ($arg) = @_;
my ($cmd, $cmddev) = FW_digestCgi($arg);
my $mod=$FW_webArgs{detail};
my $snd=$FW_webArgs{send};
my $hash = $defs{$mod};
my @args=split(" ",$snd);
@args=parse_line(' ',0,join(" ",@args));
my $ret=Signalbot_prepareSend($hash,"send",@args);
readingsSingleUpdate($hash, 'lastError', $ret,1) if defined $ret;
#$FW_XHR=1;
#This does not work als {CL} is not set here
#my $name = $hash->{NAME};
#my $web=$hash->{CL}{SNAME};
#my $peer=$hash->{CL}{PEER};
#DoTrigger($web,"JS#$peer:location.href=".'"'."?detail=$name".'"');
return 0;
}
###################################
sub Signalbot_Set($@) { #
my ( $hash, $name, @args ) = @_;
### Check Args
my $numberOfArgs = int(@args);
return "Signalbot_Set: No cmd specified for set" if ( $numberOfArgs < 1 );
my $cmd = shift @args;
my $account = ReadingsVal($name,"account","none");
my $version = $hash->{helper}{version};
return "$name not initialized" if (!defined $version);
my $multi = $hash->{helper}{multi};
my @accounts;
@accounts =@{$hash->{helper}{accountlist}} if defined $hash->{helper}{accountlist};
my $sets= "send:textField ".
"updateProfile:textField ".
"reply:textField ".
"addDevice:textField ".
"removeDevice:textField ";
$sets.= "addContact:textField ".
"createGroup:textField ".
"invite:textField ".
"block:textField ".
"unblock:textField ".
"updateGroup:textField ".
"quitGroup:textField ".
"joinGroup:textField " if $version <1000;
if ($version>=1200) {
my $ident_t="";
my $idcnt_t=1;
my $ident_u="";
foreach my $ids (keys %{$hash->{helper}{identities}}) {
if ($hash->{helper}{identities}{$ids}{TrustLevel} ne "TRUSTED_VERIFIED") {
$ident_t.= ",".$ids;
$idcnt_t++;
}
if ($hash->{helper}{identities}{$ids}{TrustLevel} eq "UNTRUSTED") {
$ident_u.= ",".$ids;
}
}
$sets.= "trustVerified:widgetList,".$idcnt_t.",select".$ident_t.",1,textField ";
$sets.= "trust:all".$ident_u." ";
}
$sets.= "group:widgetList,13,select,addMembers,removeMembers,addAdmins,removeAdmins,invite,".
"create,delete,block,unblock,update,".
"quit,join,1,textField contact:widgetList,5,select,add,delete,block,unblock,1,textField " if $version >=1000;
my $sets_reg= "link:textField ".
"register:textField ";
$sets_reg .= "captcha:textField " if defined ($hash->{helper}{register});
$sets_reg .= "verify:textField " if defined ($hash->{helper}{verification});
$sets.=$sets_reg if defined $multi && $multi==1;
$sets=$sets_reg if $account eq "none";
$sets.="signalAccount:".join(",",@accounts)." " if @accounts>0;
$sets.="reinit:noArg ";
if ( $cmd eq "?" ) {
return "Signalbot_Set: Unknown argument $cmd, choose one of " . $sets;
} # error unknown cmd handling
# Works always
if ( $cmd eq "reinit") {
my $ret = Signalbot_setup($hash);
$hash->{STATE} = $ret if defined $ret;
Signalbot_createRegfiles($hash);
return undef;
}
#Pre-parse for " " embedded strings, except for "send" that does its own processing
if ( $cmd ne "send" && $cmd ne "msg") {
@args=parse_line(' ',0,join(" ",@args));
}
#restructure multi widget command (that have a comma after the first argument)
if ( $cmd eq "group" or $cmd eq "contact") {
my @cm=split(",",$args[0]);
$cmd=$cmd.$cm[0];
$args[0]=$cm[1];
LogUnicode $hash->{NAME}, 3, $hash->{NAME}.": $cmd ".join(":",@args);
}
if ( $cmd eq "signalAccount" ) {
#When registered, first switch back to default account
my $number = shift @args;
return "Invalid number" if !defined Signalbot_checkNumber($number);;
my $ret = Signalbot_setAccount($hash, $number);
# undef is success
if (!defined $ret) {
$ret=Signalbot_setup($hash);
$hash->{STATE} = $ret if defined $ret;
return undef;
}
#if some error occured, register the old account
$ret = Signalbot_setAccount($hash,$account);
return "Error changing account, using previous account $account";
} elsif ($cmd eq "link") {
my $acname=shift @args;
$acname="FHEM" if (!defined $acname);
my $qrcode=Signalbot_CallS($hash,"link",$acname);
if (defined $qrcode) {
my $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=200x200"."&data=";
$qr_url .= uri_escape($qrcode);
$hash->{helper}{qr}=$qr_url;
$hash->{helper}{uri}=$qrcode;
$hash->{helper}{register}=undef;
$hash->{helper}{verification}=undef;
return undef;
}
return "Error creating device link:".$hash->{helper}{lasterr};
} elsif ($cmd eq "addDevice") {
my $url = shift @args;
my $ret = Signalbot_CallS($hash,"addDevice",$url);
LogUnicode $hash->{NAME}, 3 , $hash->{NAME}.": AddDevice for ".$url." returned:" .$ret;
return $ret;
} elsif ($cmd eq "removeDevice") {
my $devID = shift @args;
return Signalbot_removeDevice($hash,$devID);
} elsif ( $cmd eq "unregister") {
my $number=ReadingsVal($name,"account","");
my $vernum= shift @args;
if ($number eq $vernum) {
my $ret=Signalbot_CallS($hash,"unregister");
#delete account and do a reinit
Signalbot_disconnect($hash);
readingsSingleUpdate($hash, 'account', "none", 0);
$ret = Signalbot_setup($hash);
$hash->{STATE} = $ret if defined $ret;
Signalbot_createRegfiles($hash);
return undef;
}
return "To unregister provide current account for safety reasons";
} elsif ( $cmd eq "rateLimit") {
my $challenge= shift @args;
my $captcha= shift @args;
if (defined $challenge and defined $captcha) {
my $ret=Signalbot_CallS($hash,"submitRateLimitChallenge",$challenge,$captcha);
$hash->{STATE} = $ret if defined $ret;
return $ret;
}
} elsif ( $cmd eq "register") {
my $account= shift @args;
return "Number needs to start with '+' followed by digits" if !defined Signalbot_checkNumber($account);
delete $hash->{helper}{captcha};
$hash->{helper}{register}=$account;
$hash->{helper}{method}=0;
Signalbot_createRegfiles($hash);
my $method=AttrVal($name,"registerMethod","SMS");
if ($method eq "Voice") {
$hash->{helper}{method}=1;
}
return;
} elsif ( $cmd eq "captcha" ) {
my $captcha=shift @args;
if ($captcha =~ /signalcaptcha:\/\//) {
$hash->{helper}{captcha}=$captcha =~ s/signalcaptcha:\/\///rg;;
if (defined $account) {
my $ret=Signalbot_setCaptcha($hash);
return $ret;
}
return;
}
return "Incorrect captcha - e.g. needs to start with signalcaptcha://";
} elsif ( $cmd eq "verify" ) {
my $code=shift @args;
my $account=$hash->{helper}{verification};
if (!defined $account) {
return "You first need to complete registration before you can enter the verification code";
}
my $ret=Signalbot_CallS($hash,"verify",$account,$code);
return $hash->{helper}{lasterr} if !defined $ret;
if ($ret == 0) {
#On successfuly verification switch to that account
$ret=Signalbot_setAccount($hash,$account);
return $ret if defined $ret;
$hash->{helper}{register}=undef;
$hash->{helper}{verification}=undef;
return undef;
}
return $ret;
} elsif ( $cmd eq "addContact" || $cmd eq "contactadd") {
if (@args<2 ) {
return "Usage: set ".$hash->{NAME}." contact <number> <nickname>";
} else {
my $number = shift @args;
my $nickname = join (" ",@args);
my $ret=Signalbot_setContactName($hash,$number,$nickname);
return $ret if defined $ret;
}
return undef;
} elsif ( $cmd eq "deleteContact" || $cmd eq "contactdelete") {
return "Usage: set ".$hash->{NAME}." deleteContact <number|name>" if (@args<1);
return "signal-cli 0.10.0+ required" if $version<1000;
my $nickname = join (" ",@args);
my $number=Signalbot_translateContact($hash,$nickname);
return "Unknown contact" if !defined $number;
delete $hash->{helper}{contacts}{$number} if defined $hash->{helper}{contacts}{$number};
Signalbot_CallA($hash,"deleteContact",$number);
Signalbot_CallA($hash,"deleteRecipient",$number);
delete $hash->{helper}{contacts}{$number};
return;
} elsif ( $cmd eq "deleteGroup" || $cmd eq "groupdelete") {
return "Usage: set ".$hash->{NAME}." deleteGroup <groupname>" if (@args<1);
return "signal-cli 0.10.0+ required" if $version<1000;
my $ret=Signalbot_CallSG($hash,"deleteGroup",shift @args);
return $hash->{helper}{lasterr} if !defined $ret;
delete $hash->{helper}{groups}; #Delete the whole hash to clean up removed groups
#print "deleted" if !defined $hash->{helper}{groups};
Signalbot_refreshGroups($hash); #and read the back
return;
} elsif ( $cmd eq "addGroupMembers" || $cmd eq "groupaddMembers") {
return Signalbot_memberShip($hash,"addMembers",@args);
} elsif ( $cmd eq "removeGroupMembers" || $cmd eq "groupremoveMembers") {
return Signalbot_memberShip($hash,"removeMembers",@args);
} elsif ( $cmd eq "addGroupAdmins" || $cmd eq "groupaddAdmins") {
return Signalbot_memberShip($hash,"addAdmins",@args);
} elsif ( $cmd eq "removeGroupAdmins" || $cmd eq "groupremoveAdmins") {
return Signalbot_memberShip($hash,"removeAdmins",@args);
} elsif ( $cmd eq "createGroup" || $cmd eq "groupcreate") {
if (@args<1) {
return "Usage: set ".$hash->{NAME}." createGroup <group name> &[path to thumbnail] [member1,member2...]";
} else {
my $ret=Signalbot_updateGroup($hash,@args);
return $ret if defined $ret;
}
return undef;
} elsif ( $cmd eq "updateProfile") {
if (@args<1 || @args>2 ) {
return "Usage: set ".$hash->{NAME}." updateProfile <new name> &[path to thumbnail]";
} else {
my $ret=Signalbot_updateProfile($hash,@args);
return $ret if defined $ret;
}
return undef;
} elsif ( $cmd eq "quitGroup" || $cmd eq "groupquit") {
if (@args!=1) {
return "Usage: set ".$hash->{NAME}." ".$cmd." <group name>";
}
my @group=Signalbot_getGroup($hash,$args[0]);
return join(" ",@group) unless @group>1;
Signalbot_CallA($hash,"quitGroup",\@group);
return;
} elsif ( $cmd eq "joinGroup" || $cmd eq "groupjoin") {
if (@args!=1) {
return "Usage: set ".$hash->{NAME}." ".$cmd." <group link>";
}
Signalbot_CallA($hash,"joinGroup",$args[0]);
return;
} elsif ( $cmd eq "block" || $cmd eq "unblock" || $cmd eq "contactblock" || $cmd eq "contactunblock" || $cmd eq "groupblock" || $cmd eq "groupunblock") {
if (@args!=1) {
return "Usage: set ".$hash->{NAME}." ".$cmd." <group name>|<contact>";
} else {
my $name=shift @args;
my $ret=Signalbot_setBlocked($hash,$name,(($cmd=~ /unblock/)?0:1));
return $ret if defined $ret;
}
return undef;
} elsif ( $cmd eq "updateGroup" || $cmd eq "groupupdate") {
if (@args<1 || @args>3 ) {
return "Usage: set ".$hash->{NAME}." updateGroup <group name> #[new name] &[path to thumbnail]";
} else {
my $ret=Signalbot_updateGroup($hash,@args);
return $ret if defined $ret;
}
return undef;
} elsif ( $cmd eq "invite" || $cmd eq "groupinvite") {
if (@args < 2 ) {
return "Usage: set ".$hash->{NAME}." invite <group name> <contact1> [<contact2] ...]";
} else {
my $groupname = shift @args;
my $ret=Signalbot_invite($hash,$groupname,@args);
return $ret if defined $ret;
}
return undef;
} elsif ( $cmd eq "trust" ) {
my $number = shift @args;
return "not implemented" if $number eq "all";
my $ret=Signalbot_CallSI($hash,"trust",$number);
return $ret;
} elsif ( $cmd eq "trustVerified") {
my @cm = split(",",$args[0]);
my $ret=Signalbot_CallSI($hash,"trustVerified",$cm[0],$cm[1]);
return $ret;
} elsif ( $cmd eq "send" || $cmd eq "reply" || $cmd eq "msg") {
return "Usage: set ".$hash->{NAME}." send [@<Recipient1> ... @<RecipientN>] [#<GroupId1> ... #<GroupIdN>] [&<Attachment1> ... &<AttachmentN>] [<Text>]" if ( @args==0);
return Signalbot_prepareSend($hash,$cmd,@args);
}
return "Unknown command $cmd";
}
sub Signalbot_memberShip($@) {
my ($hash,$func,@args) = @_;
return "Usage: set ".$hash->{NAME}." $func <groupname> <contact1> [contact2] ..." if (@args<2);
my $version = $hash->{helper}{version};
return "signal-cli 0.10.0+ required" if $version<1000;
my $group=shift @args;
my @contacts;
foreach my $contact (@args) {
my $c=Signalbot_translateContact($hash,$contact);
return "Unknown contact $contact" if !defined $c;
push @contacts,$c;
}
Signalbot_CallAG($hash,$func,$group,\@contacts);
return;
}
sub Signalbot_prepareSend($@) {
my ($hash,$cmd,@args)= @_;
my @recipients = ();
my @groups = ();
my @attachments = ();
my $message = "";
#To allow spaces in strings, join string and split it with parse_line that will honor spaces embedded by double quotes
my $fullstring=join(" ",@args);
my $bExclude=AttrVal($hash->{NAME},"babbleExclude",undef);
if ($bExclude && $fullstring =~ /$bExclude(.*)/s) { #/s required so newlines are included in match
#Extra utf Encoding marker)
#$fullstring=encode_utf8($1);
#Log3 $hash->{NAME}, 4 , $hash->{NAME}.": Extra UTF8 encoding of:$fullstring:\n";
}
#$fullstring=encode_utf8($fullstring) if($unicodeEncoding);
eval { $fullstring=decode_utf8($fullstring) if !($unicodeEncoding)};
# Log3 $hash->{NAME}, 3 , $hash->{NAME}.": Error from decode" if $@;
LogUnicode $hash->{NAME}, 3 , $hash->{NAME}.": Before parse:" .$fullstring. ":";
my $tmpmessage = $fullstring =~ s/\\n/\x0a/rg;
@args=parse_line(' ',0,$tmpmessage);
while(my $curr_arg = shift @args){
if($curr_arg =~ /^\@([^#].*)$/){ #Compatbility with SiSi - also allow @# as groupname
push(@recipients,$1);
}elsif($curr_arg =~ /^\@#(.*)$/){ #Compatbility with SiSi - also allow @# as groupname
push(@groups,$1);
}elsif($curr_arg =~ /^#(.*)$/){
push(@groups,$1);
}elsif($curr_arg =~ /^\&(.*)$/){
push(@attachments,$1);
}else{
unshift(@args,$curr_arg);
last;
}
}
my $defaultPeer=AttrVal($hash->{NAME},"defaultPeer",undef);
if ($cmd eq "reply") {
my $lastSender=ReadingsVal($hash->{NAME},"msgGroupName","");
if ($lastSender ne "") {
$lastSender="#".$lastSender;
} else {
$lastSender=ReadingsVal($hash->{NAME},"msgSender","");
}
$defaultPeer=$lastSender if $lastSender ne "";
Log3 $hash->{NAME}, 4 , $hash->{NAME}.": Reply mode to $defaultPeer";
}
return "Not enough arguments. Specify a Recipient, a GroupId or set the defaultPeer attribute" if( (@recipients==0) && (@groups==0) && (!defined $defaultPeer) );
#Check for embedded fhem/perl commands
my $err;
($err, @recipients) = Signalbot_replaceCommands($hash,@recipients);
if ($err) { return $err; }
($err, @groups) = Signalbot_replaceCommands($hash,@groups);
if ($err) { return $err; }
($err, @attachments) = Signalbot_replaceCommands($hash,@attachments);
if ($err) { return $err; }
if ((defined $defaultPeer) && (@recipients==0) && (@groups==0)) {
my @peers = split(/,/,$defaultPeer);
while(my $curr_arg = shift @peers){
if($curr_arg =~ /^#/){
push(@groups,$curr_arg);
} else {
push(@recipients,$curr_arg);
}
}
}
return "Specify either a message text or an attachment" if((@attachments==0) && (@args==0));
$message = join(" ", @args);
my @orgatt=@attachments;
if (@attachments>0) {
#create copy in /tmp to mitigate incomplete files and relative paths in fhem
my @newatt;
foreach my $file (@attachments) {
if ( -e $file ) {
if ($file=~/^\/tmp\/signalbot.*/ ne 1) {
$file =~ /^.*?\.([^.]*)?$/;
my $type = $1;
my $tmpfilename="/tmp/signalbot".gettimeofday().".".$type;
copy($file,$tmpfilename);
push @newatt, $tmpfilename;
} else {
push @newatt, $file;
}
} else {
my $png=Signalbot_getPNG($hash,$file);
return "File not found: $file" if !defined $png;
return $png if ($png =~ /^Error:.*/);
push @newatt, $png;
}
}
@attachments=@newatt;
}
#Convert html or markdown to unicode
my $format=AttrVal($hash->{NAME},"formatting","none");
my $convmsg=formatTextUnicode($format,$message);
$message=$convmsg if defined $convmsg;
my $ret;
#Send message to individuals (bulk)
if (@recipients > 0) {
$ret=Signalbot_sendMessage($hash,join(",",@recipients),join(",",@attachments),$message);
foreach my $sender (@recipients) {
Signalbot_AddToChat($hash,"Me",$sender,"",$message.(@attachments>0?"(".join(",",@orgatt).")":""));
}
}
if (@groups > 0) {
#Send message to groups (one at time)
while(my $currgroup = shift @groups){
$ret=Signalbot_sendGroupMessage($hash,$currgroup,join(",",@attachments),$message);
Signalbot_AddToChat($hash,"Me","",$currgroup,$message.(@attachments>0?"(".join(",",@orgatt).")":""));
}
}
#Remember temp files
my @atts = ();
my $attstore = $hash->{helper}{attachments};
if (defined $attstore) {
@atts = @$attstore;
}
push @atts,@attachments;
$hash->{helper}{attachments}=[@atts];
return $ret;
}
###################################
sub Signalbot_Get($@) {
my ($hash, $name, @args) = @_;
my $version = $hash->{helper}{version};
return "$name not initialized" if (!defined $version);
my $numberOfArgs = int(@args);
return "Signalbot_Get: No cmd specified for get" if ( $numberOfArgs < 1 );
my $cmd = shift @args;
my $account = ReadingsVal($name,"account","none");
if ($cmd eq "?") {
my $gets="favorites:noArg accounts:noArg helpUnicode:noArg ";
$gets.="contacts:all,nonblocked ".
"groups:all,active,nonblocked devices:noArg " if $account ne "none";
my $chat_t="";
my $chat_cnt=0;
foreach my $chat (keys %{$hash->{helper}{chat}}) {
$chat_t.="," if $chat_cnt>0;
$chat_t.=$chat;
$chat_cnt++;
}
if ($chat_cnt>0) {
$chat_t=~s/ / /g;
$gets.= "chat:".($chat_cnt<20?$chat_t:"textField")." ";
}
my $group_t="";
my $grcnt_t=0;
foreach my $group (keys %{$hash->{helper}{groups}}) {
$group_t.="," if $grcnt_t>0;
$group_t.=$hash->{helper}{groups}{$group}{name};
$grcnt_t++;
}
if ($grcnt_t>0) {
$group_t=~s/ / /g;
$gets.= "groupProperties:".($grcnt_t<20?$group_t:"textField")." ";
}
if ($version>=1200) {
my $ident_t="";
my $idcnt_t=0;
foreach my $number (keys %{$hash->{helper}{identities}}) {
$ident_t.="," if $idcnt_t>0;
$ident_t.= $number;
if (exists $hash->{helper}{contacts}{$number}) {
my $cname=$hash->{helper}{contacts}{$number} ne ""?$hash->{helper}{contacts}{$number}:"Unknown";
$ident_t.="($cname)";
}
$idcnt_t++;
}
$ident_t=~s/ /_/g;
$gets.= "identityDetails:".($idcnt_t<20?$ident_t:"textField")." ";
}
return "Signalbot_Get: Unknown argument $cmd, choose one of ".$gets;
}
my $arg = shift @args;
if ($cmd eq "introspective") {
my $reply=Signalbot_CallS($hash,"org.freedesktop.DBus.Introspectable.Introspect");
return undef;
} elsif ($cmd eq "helpUnicode") {
return demoUnicodeHTML();
} elsif ($cmd eq "accounts") {
my $num=Signalbot_getAccounts($hash);
return "Error in listAccounts" if $num<0;
my $ret="List of registered accounts:\n\n";
my @numlist=@{$hash->{helper}{accountlist}};
$ret=$ret.join("\n",@numlist);
return $ret;
} elsif ($cmd eq "devices") {
my $ret=Signalbot_CallS($hash,"listDevices");
my $str="Linked devices:\n\n";
foreach my $dev (@$ret) {
my ($devpath,$devid,$devname)=@$dev;
if ($devid eq 1 && $devname eq "") {
$devname="main device";
}
$str.=sprintf("%2i %s\n",$devid,$devname);
}
return $str;
} elsif ($cmd eq "identityDetails") {
$arg=~/(^.*)(\(.*\)$)/;
my $number;
if ($1) {
$number=$1;
} else {
$number=$arg;
}
my $str="Details for $number\n\n";
if ($number =~ /^\+[1-9][0-9]{5,}$/) {
my $contact=Signalbot_getContactName($hash,$number);
my $path=Signalbot_getIdentityPath($hash,$number);
return "Unknown identity ".$number if !defined $path;
my $ret=Signalbot_getIdentityProperties($hash,$path);
if (defined $ret) {
my %props=%$ret;
$str.="Contact Name :".$contact."\n";
$str.="Trust Level :".$props{TrustLevel}."\n";
$str.="Safety Number :".$props{SafetyNumber}."\n";
#Don't display as it is very long and not sure what it's used for anyway
my $fp=$props{Fingerprint};
#$str.="Fingerprint :".join(" ",@$fp)."\n";
$str.="Added date :". strftime("%d-%m-%Y %H:%M:%S", localtime($props{AddedDate}/1000))."\n";
my $sf=$props{ScannableSafetyNumber};
my $cstr=pack("C*",@$sf);
my $fn=Signalbot_copyToFile($cstr,"dat");
unlink "www/signal/qr.png";
my $ret=qx(qrencode -r $fn -o www/signal/qr.png);
unlink $fn;
if (-e "www/signal/qr.png") {
$str.="Scannable Safety Number to validate FHEM from Mobile:\n";
my $qr_url .= "fhem/signal/qr.png?".gettimeofday(); #adding timestamp to prevent image caching by the browser
$str .= "<a href=\"$qr_url\"><img src=\"$qr_url\"><\/a><br>";
} else {
$str.="Could not generate QR Code. Check if qrencode is installed.\n".$ret."\n";
}
}
}
return $str;
} elsif ($cmd eq "chat") {
my $ret="";
my $chat=$hash->{helper}{chat}{$arg};
if (defined $chat) {
$ret.="Chat history with $arg\n\n";
$ret.=$chat;
} else {
$ret="No chat history with $arg";
}
return $ret;
} elsif ($cmd eq "favorites") {
my $favs = AttrVal($name,"favorites","");
$favs =~ s/[\n\r]//g;
$favs =~ s/;;/##/g;
my @fav=split(";",$favs);
return "No favorites defined" if @fav==0;
my $ret="Defined favorites:\n\n";
my $format="%2i (%s) %-15s %-50s\n";
$ret.="ID (A) Alias Command\n";
my $cnt=1;
foreach (@fav) {
my $ff=$_;
$ff =~ /(^\[(.*?)\])?([\-]?)(.*)/;
my $aa="y";
if ($3 eq "-") {
$aa="n";
}
my $alias=$2;
$alias="" if !defined $2;
my $favs=$4;
$favs =~ s/##/;;/g;
$ret.=sprintf($format,$cnt,$aa,$alias,$favs);
$cnt++;
}
$ret.="\n(A)=GoogleAuth required to execute command";
return $ret;
} elsif ($cmd eq "contacts" && defined $arg) {
my $num=Signalbot_CallS($hash,"listNumbers");
return $hash->{helper}{lasterr} if !defined $num;
my @numlist=@$num;
my $ret="List of known contacts:\n\n";
my $format="%-16s|%-30s|%-6s\n";
$ret.=sprintf($format,"Number","Name","Blocked");
$ret.="\n";
foreach my $number (@numlist) {
my $blocked=Signalbot_CallS($hash,"isContactBlocked",$number);
return $hash->{helper}{lasterr} if !defined $blocked;
my $name=$hash->{helper}{contacts}{$number};
if (!defined $name) {
$name=Signalbot_getContactName($hash,$number);
}
$name="UNKNOWN" if ($name =~/^\+/);
if (! ($number =~ /^\+/) ) { $number="Unknown"; }
if ($arg eq "all" || $blocked==0) {
$ret.=sprintf($format,$number,$name,$blocked==1?"yes":"no");
}
}
return $ret;
} elsif ($cmd eq "groups" && defined $arg) {
Signalbot_refreshGroups($hash);
my $ret="List of known groups:\n\n";
my $memsize=40;
my $format="%-20.20s|%-6.6s|%-7.7s|%-".$memsize.".".$memsize."s\n";
$ret.=sprintf($format,"Group","Active","Blocked","Members");
$ret.="\n";
foreach my $groupid (keys %{$hash->{helper}{groups}}) {
my $blocked=$hash->{helper}{groups}{$groupid}{blocked};
my $active=$hash->{helper}{groups}{$groupid}{active};
my $group=$hash->{helper}{groups}{$groupid}{name};
my @groupID=split(" ",$groupid);
my $mem=Signalbot_CallS($hash,"getGroupMembers",\@groupID);
return $hash->{helper}{lasterr} if !defined $mem;
my @members=();;
foreach (@$mem) {
push @members,Signalbot_getContactName($hash,$_);
}
if ($arg eq "all" || ($active==1 && $arg eq "active") || ($active==1 && $blocked==0 && $arg eq "nonblocked") ) {
my $mem=join(",",@members);
$ret.=sprintf($format,$group,$active==1?"yes":"no",$blocked==1?"yes":"no",substr($mem,0,$memsize));
my $cnt=1;
while (length($mem)>$cnt*$memsize) {
$ret.=sprintf($format,"","","",substr($mem,$cnt*$memsize,$cnt*$memsize+$memsize));
$cnt++;
}
}
}
return $ret;
} elsif ($cmd eq "groupProperties") {
return if $version<1000;
$arg=decode_utf8($arg); #required to fully replace  
$arg=~s/$&\x{00a0}/ /g; #Restore normal spaces
my $ret=Signalbot_getGroupProperties($hash,$arg);
return "Error:".$hash->{helper}{lasterr} if !defined $ret;
my %props=%$ret;
$ret="Group $arg\n==============================\n";
$ret.="Description:".$props{Description}."\n";
$ret.="IsMember:".(($props{IsMember}==1)?"yes":"no")."\n";
$ret.="SendMessage:".$props{PermissionSendMessage}."\n";
$ret.="EditDetails:".$props{PermissionEditDetails}."\n";
$ret.="IsBlocked:".(($props{IsBlocked}==1)?"yes":"no")."\n";
$ret.="IsAdmin:".(($props{IsAdmin}==1)?"yes":"no")."\n";
my $members=$props{Members};
$ret .="\nMembers:".join(",",Signalbot_contactsToList($hash,@$members));
$members=$props{RequestingMembers};
$ret .="\nRequesting members:".join(",",Signalbot_contactsToList($hash,@$members));
$members=$props{Admins};
$ret .="\nAdmins:".join(",",Signalbot_contactsToList($hash,@$members));
$members=$props{PendingMembers};
$ret .="\nPending members:".join(",",Signalbot_contactsToList($hash,@$members));
return $ret;
}
return undef;
}
sub Signalbot_contactsToList($@) {
my ($hash,@con) = @_;
my @list;
foreach (@con) {
push @list,Signalbot_getContactName($hash,$_);
}
return @list;
}
sub Signalbot_command($@){
my ($hash, $sender, $message) = @_;
LogUnicode $hash->{NAME}, 5, $hash->{NAME}.": Check Command $sender $message";
my $timeout=AttrVal($hash->{NAME},"authTimeout",300);
return $message if $timeout==0;
my $cmd=AttrVal($hash->{NAME},"cmdKeyword",undef);
return $message unless defined $cmd;
my $trust=0;
if (exists $hash->{helper}{identities}{$sender} and exists $hash->{helper}{identities}{$sender}{TrustLevel} and
$hash->{helper}{identities}{$sender}{TrustLevel} eq "TRUSTED_VERIFIED" and AttrVal($hash->{NAME},"authTrusted","no") eq "yes") {
$trust=1;
LogUnicode $hash->{NAME}, 5, $hash->{NAME}.": $sender is trusted";
} else {
LogUnicode $hash->{NAME}, 5, $hash->{NAME}.": $sender is not trusted";
}
my @arr=();
if ($message =~ /^$cmd(.*)/) {
$cmd=$1;
LogUnicode $hash->{NAME}, 5, $hash->{NAME}.": Command received:$cmd";
my $device=AttrVal($hash->{NAME},"authDev",undef);
if (!defined $device and $trust==0) {
readingsSingleUpdate($hash, 'lastError', "Missing GoogleAuth device in authDev to execute remote command",1);
return $message;
}
my @cc=split(" ",$cmd);
if ($cc[0] =~ /^\d+$/) {
my $restcmd=join(" ",@cc);
if ($trust == 0) {
#This could be a token
my $token=shift @cc;
my $ret = gAuth($device,$token);
if ($ret == 1) {
LogUnicode $hash->{NAME}, 5, $hash->{NAME}.": Token valid for sender $sender for $timeout seconds";
$hash->{helper}{auth}{$sender}=1;
#Remove potential old timer so countdown start from scratch
RemoveInternalTimer("$hash->{NAME} $sender");
InternalTimer(gettimeofday() + $timeout, 'Signalbot_authTimeout', "$hash->{NAME} $sender", 0);
Signalbot_sendMessage($hash,$sender,"","You have control for ".$timeout."s");
$cmd=$restcmd;
} else {
LogUnicode $hash->{NAME}, 3, $hash->{NAME}.": Invalid token sent by $sender";
$hash->{helper}{auth}{$sender}=0;
Signalbot_sendMessage($hash,$sender,"","Invalid token");
LogUnicode $hash->{NAME}, 2, $hash->{NAME}.": Invalid token sent by $sender:$message";
return $cmd;
}
}
}
my $auth=$trust;
if (defined $hash->{helper}{auth}{$sender} && $hash->{helper}{auth}{$sender}==1) {
$auth=1;
}
my $fav=AttrVal($hash->{NAME},"cmdFavorite",undef);
$fav =~ /^(-?)(.*)/;
my $authList=$1;
$fav = $2;
my $error="";
if (defined $fav && defined $cc[0] && $cc[0] eq $fav) {
shift @cc;
my $fav=AttrVal($hash->{NAME},"favorites","");
eval { $fav=decode_utf8($fav) if !($unicodeEncoding)};
$fav =~ s/[\n\r]//g;
$fav =~ s/;;/##/g;
my @favorites=split(";",$fav);
if (@cc>0) {
LogUnicode $hash->{NAME}, 4, $hash->{NAME}.": $sender executes favorite command $cc[0]";
if ($cc[0] =~/\d+$/) {
#Favorite by index
my $fid=$cc[0]-1;
if ($fid<@favorites) {
$cmd=$favorites[$fid];
$cmd =~ /(^\[.*?\])?([\-]?)(.*)/;
$cmd=$3 if defined $3;
#"-" defined favorite commands that do not require authentification
$auth=1 if (defined $2 && $2 eq "-");
LogUnicode $hash->{NAME}, 4, $hash->{NAME}.": $sender requests favorite command:$cmd";
} else {
$cmd="";
$error="favorite #$cc[0] not defined";
}
} else {
my $alias=join(" ",@cc);
$cmd="";
foreach my $ff (@favorites) {
$ff =~ /(^\[(.*?)\])?([\-]?)(.*)/;
if (defined $2 && $2 eq $alias) {
$cmd=$4 if defined $4;
#"-" defined favorite commands that do not require authentification
$auth=1 if (defined $3 && $3 eq "-");
}
}
if ($cmd eq "") {
$error="favorite '$alias' not defined";
}
}
} else {
my $ret="Defined favorites:\n\n";
$ret.="ID [Alias] Command\n";
my $cnt=1;
foreach (@favorites) {
my $ff=$_;
$ff =~ s/##/;;/g;
$ff =~ /(^\[(.*?)\])?([\-]?)(.*)/;
my $fav=$4;
$fav =$1." ".$fav if defined $1;
$fav =sprintf("%2i %s",$cnt,$fav);
$fav =substr($fav,0,25)."..." if length($fav)>27;
$ret.=$fav."\n";
$cnt++;
}
$ret="No favorites defined" if @favorites==0;
if ($auth || $authList eq "-") {
Signalbot_sendMessage($hash,$sender,"",$ret);
return $cmd;
}
$cmd="";
}
}
# Always return the same message if not authorized
if (!$auth) {
readingsSingleUpdate($hash, 'lastError', "Unauthorized command request by $sender:$message",1);
LogUnicode $hash->{NAME}, 2, $hash->{NAME}.": Unauthorized command request by $sender:$message";
Signalbot_sendMessage($hash,$sender,"","You are not authorized to execute commands");
return $cmd;
}
# If authorized return errors via Signal and Logfile
if ($error ne "") {
Signalbot_sendMessage($hash,$sender,"",$error);
#Log3 $hash->{NAME}, 4, $hash->{NAME}.": $error";
}
return $cmd if $cmd eq "";
LogUnicode $hash->{NAME}, 4, $hash->{NAME}.": $sender executes command $cmd";
$cmd =~ s/##/;/g;
my %dummy;
my ($err, @a) = ReplaceSetMagic(\%dummy, 0, ( $cmd ) );
if ( $err ) {
LogUnicode $hash->{NAME}, 4, $hash->{NAME}.": parse cmd failed on ReplaceSetmagic with :$err: on :$cmd:";
} else {
$cmd = join(" ", @a);
LogUnicode $hash->{NAME}, 4, $hash->{NAME}.": parse cmd returned :$cmd:";
}
if ($cmd =~ /^print (.*)/) {
$error=$1; #ReplaceSetMagic has already modified the string, treat it as error to send
$cmd="";
}