forked from viegener/Telegram-fhem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path70_Telegram.pm
1213 lines (982 loc) · 39.3 KB
/
70_Telegram.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
##############################################################################
#
# 70_Telegram.pm
#
# This file is part of Fhem.
#
# Fhem is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Fhem is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fhem. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#
# Telegram (c) Johannes Viegener / https://github.com/viegener/Telegram-fhem
#
# This module handles receiving and sending messages to the messaging service telegram (see https://telegram.org/)
# It works ONLY with a running telegram-cli (unofficial telegram cli client) --> see here https://github.com/vysheng/tg
# telegram-cli needs to be configured and running as daemon local on the fhem host
#
##############################################################################
# 0.0 2015-06-16 Started
#
# Build structure for module
# telegram-cli for operation
# Basic DevIo handling
# Attributes etc
# Allow message sending to defaultpeer
# basic telegram_read for only putting message into reading
# 0.1 2015-06-17 Initial Version
#
# General command handling analyzing results
# _write function
# handle initialization (client write / main session) in DoInit
# allow host
# shutdown function added to send quit on connection
# Telegram_read
# handle readings
# document cli command
# document attr/set/get
# documentation on limitations
# 0.2a 2015-06-19 Running basic version with send and receive
# corrections and stabilizations on message receive
# 0.2b 2015-06-20 Update
#
# works after rereadcfg
# DoCommand reimplemented
# Cleaned also the read function
# add raw as set command to execute a raw command on the telegram-cli
# get msgid now implemented
# renamed msg set/get into message (set) and msgById (get)
# added readyfn for handling remaining internal
# 0.3 2015-06-20 stabilized
#
# sent to any peer with set messageTo
# reopen connection is done automatically through DevIo
# document telegram-cli command in more detail
# added zDebug set for internal cleanup work (currently clean remaining)
# parse also secret chat messages
# request default peer to be given with underscore not space
# Read will parse now all remaining messages and run multiple bulk updates in a row for each mesaage one
# lastMessage moved from Readings to Internals
# BUG resolved: messages are split wrongly (A of ANSWER might be cut)
# updated git hub link
# allow secret chat / new attr defaultSecret to send messages to defaultPeer via secret chat
# 0.4 2015-06-22 SecretChat and general extensions and cleanup
#
# new set command sendPhoto to send images
# prepare new attributes for command handling on sent messages
# FIX read message routine, ensure remaining is updated
# enable commands through messages --> AnalyzeCommand
# restrict commands by peer
# restrict commands to trigger only
# 0.5 2015-07-12 SecretChat and general extensions and cleanup
#
# FIX call _Read in DoCommand to ensure other remaining pieces are read
# was only worked off when new data was received from port
# Remove Read test on remaining
# Fix: restrictedPeer will lead to log message and is now allowing string value
# format msgPeer peer format with underscore to be reusable in msgTo
# prepare for dealing with numeric chat and user ids
# only a simgle message and without preceding ANSWER and length (if complete) will be returned as results of raw commands (and other ocmmands)
# allow multiple restrictedPeers for cmds
# remove lastMsgId (was not handled so far)
# 0.6 2015-08-07 Stabilization
#
# remove write fn (not needed for logical device)
# FIX: quit command on shutdown
# Send command result also to sender of command
# Send name of peer with command result
# FIX: handled undefined buf in docommmand on startup
# new set command sendPhotoTo - sending message to an arbitrary peer
# longer delay for doCommand (.5 sec) to allow success or failure being sent
# Internal: reworked set to use a joint send_phote/message routine
# command results parsing: cr/lf will be replaced by spaces
# 0.7 2015-09-27 SendPhotoTo / better Command handling
#
#
##############################################################################
# Extensions
# - handle recursion by marking entry into _set / _get / _attr / _read ; remaining messages only handled on entry into recursion
# - startup behavior: make sure being able to be operational and able to send a message
# - handle numeric ID mode of telegram-cli (increased security due to fixed identities)
# - fix telegramd script to ensure port being shutdown
# - test socket handling
#
##############################################################################
# Ideas / Future
# - read all unread messages from default peer on init
# - allow multi parameter set for set <device> <peer>
# - start local telegram-cli as subprocess
# - support presence messages
# - add contact
#
##############################################################################
#
# Internals
# - Internal: sentMsgText
# - Internal: sentMsgResult
# - Internal: sentMsgPeer
# - Internal: sentMsgSecure
# - Internal: REMAINING - used for storing messages received intermediate
# - Internal: lastmessage - last message handled in Read function
# - Internal: sentMsgId???
#
##############################################################################
package main;
use strict;
use warnings;
use DevIo;
use Scalar::Util qw(reftype looks_like_number);
#########################
# Forward declaration
sub Telegram_Define($$);
sub Telegram_Undef($$);
sub Telegram_Set($@);
sub Telegram_Get($@);
sub Telegram_Read($;$);
sub Telegram_Parse($$$);
#########################
# Globals
my %sets = (
"message" => "textField",
"secretChat" => undef,
"messageTo" => "textField",
"raw" => "textField",
"sendPhoto" => "textField",
"sendPhotoTo" => "textField",
"zDebug" => "textField"
);
my %gets = (
"msgById" => "textField"
);
#####################################
# Initialize is called from fhem.pl after loading the module
# define functions and attributed for the module and corresponding devices
sub Telegram_Initialize($) {
my ($hash) = @_;
require "$attr{global}{modpath}/FHEM/DevIo.pm";
$hash->{ReadFn} = "Telegram_Read";
# $hash->{WriteFn} = "Telegram_Write";
$hash->{ReadyFn} = "Telegram_Ready";
$hash->{DefFn} = "Telegram_Define";
$hash->{UndefFn} = "Telegram_Undef";
$hash->{GetFn} = "Telegram_Get";
$hash->{SetFn} = "Telegram_Set";
$hash->{ShutdownFn} = "Telegram_Shutdown";
$hash->{AttrFn} = "Telegram_Attr";
$hash->{AttrList} = "defaultPeer defaultSecret:0,1 cmdKeyword cmdRestrictedPeer cmdTriggerOnly:0,1 cmdNumericIDs:0,1".
$readingFnAttributes;
}
######################################
# Define function is called for actually defining a device of the corresponding module
# For telegram this is mainly the name and information about the connection to the telegram-cli client
# data will be stored in the hash of the device as internals
#
sub Telegram_Define($$) {
my ($hash, $def) = @_;
my @a = split("[ \t]+", $def);
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_Define $name: called ";
my $errmsg = '';
# Check parameter(s)
if( int(@a) != 3 ) {
$errmsg = "syntax error: define <name> Telegram <port> ";
Log3 $name, 3, "Telegram $name: " . $errmsg;
return $errmsg;
}
if ( $a[2] =~ /^([[:alnum:]][[:alnum:]-]*):[[:digit:]]+$/ ) {
$hash->{DeviceName} = $a[2];
} elsif ( $a[2] =~ /:/ ) {
$errmsg = "specify valid hostname and numeric port: define <name> Telegram [<hostname>:]<port> ";
Log3 $name, 3, "Telegram $name: " . $errmsg;
return $errmsg;
} elsif (! looks_like_number($a[2])) {
$errmsg = "port needs to be numeric: define <name> Telegram [<hostname>:]<port> ";
Log3 $name, 3, "Telegram $name: " . $errmsg;
return $errmsg;
} else {
$hash->{DeviceName} = "localhost:$a[2]";
}
$hash->{TYPE} = "Telegram";
$hash->{Port} = $a[2];
$hash->{Protocol} = "telnet";
# close old dev
Log3 $name, 5, "Telegram_Define $name: handle DevIO ";
DevIo_CloseDev($hash);
my $ret = DevIo_OpenDev($hash, 0, "Telegram_DoInit");
### initialize timer for connectioncheck
#$hash->{helper}{nextConnectionCheck} = gettimeofday()+120;
Log3 $name, 5, "Telegram_Define $name: done with ".(defined($ret)?$ret:"undef");
return $ret;
}
#####################################
# Undef function is corresponding to the delete command the opposite to the define function
# Cleanup the device specifically for external ressources like connections, open files,
# external memory outside of hash, sub processes and timers
sub Telegram_Undef($$)
{
my ($hash, $arg) = @_;
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_Undef $name: called ";
RemoveInternalTimer($hash);
# deleting port for clients
foreach my $d (sort keys %defs) {
if(defined($defs{$d}) &&
defined($defs{$d}{IODev}) &&
$defs{$d}{IODev} == $hash) {
Log3 $hash, 3, "Telegram $name: deleting port for $d";
delete $defs{$d}{IODev};
}
}
Log3 $name, 5, "Telegram_Undef $name: close devio ";
DevIo_CloseDev($hash);
Log3 $name, 5, "Telegram_Undef $name: done ";
return undef;
}
######################################
# Shutdown function is called on shutdown of server and will issue a quite to the cli
sub Telegram_Shutdown($) {
my ( $hash ) = @_;
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_Attr $name: called ";
# First needs send an empty line and read all returns away
my $buf = Telegram_DoCommand( $hash, '', undef );
# send a quit but ignore return value
$buf = Telegram_DoCommand( $hash, 'quit', undef );
Log3 $name, 5, "Telegram_Shutdown $name: Done quit with return :".(defined($buf)?$buf:"undef").": ";
return undef;
}
##############################################################################
##############################################################################
## Instance operational methods
##############################################################################
##############################################################################
####################################
# set function for executing set operations on device
sub Telegram_Set($@)
{
my ( $hash, $name, @args ) = @_;
Log3 $name, 5, "Telegram_Set $name: called ";
### Check Args
my $numberOfArgs = int(@args);
return "Telegram_Set: No value specified for set" if ( $numberOfArgs < 1 );
my $cmd = shift @args;
Log3 $name, 5, "Telegram_Set $name: Processing Telegram_Set( $cmd )";
if(!exists($sets{$cmd})) {
my @cList;
foreach my $k (sort keys %sets) {
my $opts = undef;
$opts = $sets{$k};
if (defined($opts)) {
push(@cList,$k . ':' . $opts);
} else {
push (@cList,$k);
}
} # end foreach
return "Telegram_Set: Unknown argument $cmd, choose one of " . join(" ", @cList);
} # error unknown cmd handling
my $ret = undef;
if($cmd eq 'message') {
if ( $numberOfArgs < 2 ) {
return "Telegram_Set: Command $cmd, no text specified";
}
my $peer = AttrVal($name,'defaultPeer',undef);
if ( ! defined($peer) ) {
return "Telegram_Set: Command $cmd, requires defaultPeer being set";
}
# should return undef if succesful
Log3 $name, 5, "Telegram_Set $name: start message send ";
my $arg = join(" ", @args );
$ret = Telegram_SendIt( $hash, $peer, $arg, 1 );
} elsif($cmd eq 'messageTo') {
if ( $numberOfArgs < 3 ) {
return "Telegram_Set: Command $cmd, need to specify peer and text ";
}
# should return undef if succesful
my $peer = shift @args;
my $arg = join(" ", @args );
Log3 $name, 5, "Telegram_Set $name: start message send ";
$ret = Telegram_SendIt( $hash, $peer, $arg, 1 );
} elsif($cmd eq 'raw') {
if ( $numberOfArgs < 2 ) {
return "Telegram_Set: Command $cmd, no raw command specified";
}
my $arg = join(" ", @args );
Log3 $name, 5, "Telegram_Set $name: start rawCommand :$arg: ";
$ret = Telegram_DoCommand( $hash, $arg, undef );
} elsif($cmd eq 'secretChat') {
if ( $numberOfArgs > 1 ) {
return "Telegram_Set: Command $cmd, no parameters allowed";
}
my $peer = AttrVal($name,'defaultPeer',undef);
if ( ! defined($peer) ) {
return "Telegram_Set: Command $cmd, requires defaultPeer being set";
}
Log3 $name, 5, "Telegram_Set $name: initiate secret chat with :$peer: ";
my $statement = "create_secret_chat ".$peer;
$ret = Telegram_DoCommand( $hash, $statement, undef );
} elsif($cmd eq 'sendPhoto') {
if ( $numberOfArgs < 2 ) {
return "Telegram_Set: Command $cmd, need to specify filename ";
}
# should return undef if succesful
my $peer = AttrVal($name,'defaultPeer',undef);
if ( ! defined($peer) ) {
return "Telegram_Set: Command $cmd, requires defaultPeer being set";
}
my $arg = join(" ", @args );
Log3 $name, 5, "Telegram_Set $name: start photo send ";
$ret = Telegram_SendIt( $hash, $peer, $arg, 0 );
} elsif($cmd eq 'sendPhotoTo') {
if ( $numberOfArgs < 3 ) {
return "Telegram_Set: Command $cmd, need to specify peer and text ";
}
# should return undef if succesful
my $peer = shift @args;
my $arg = join(" ", @args );
Log3 $name, 5, "Telegram_Set $name: start photo send to $peer";
$ret = Telegram_SendIt( $hash, $peer, $arg, 0 );
} elsif($cmd eq 'zDebug') {
Log3 $name, 5, "Telegram_Set $name: start debug option ";
# delete( $hash->{READINGS}{lastmessage} );
# delete( $hash->{READINGS}{prevMsgSecret} );
# delete( $hash->{REMAININGOLD} );
}
if ( ! defined( $ret ) ) {
Log3 $name, 5, "Telegram_Set $name: $cmd done succesful: ";
} else {
Log3 $name, 5, "Telegram_Set $name: $cmd failed with :$ret: ";
}
return $ret
}
#####################################
# get function for gaining information from device
sub Telegram_Get($@)
{
my ( $hash, $name, @args ) = @_;
Log3 $name, 5, "Telegram_Get $name: called ";
### Check Args
my $numberOfArgs = int(@args);
return "Telegram_Get: No value specified for get" if ( $numberOfArgs < 1 );
my $cmd = $args[0];
my $arg = ($args[1] ? $args[1] : "");
Log3 $name, 5, "Telegram_Get $name: Processing Telegram_Get( $cmd )";
if(!exists($gets{$cmd})) {
my @cList;
foreach my $k (sort keys %gets) {
my $opts = undef;
$opts = $sets{$k};
if (defined($opts)) {
push(@cList,$k . ':' . $opts);
} else {
push (@cList,$k);
}
} # end foreach
return "Telegram_Get: Unknown argument $cmd, choose one of " . join(" ", @cList);
} # error unknown cmd handling
my $ret = undef;
if($cmd eq 'msgById') {
if ( $numberOfArgs != 2 ) {
return "Telegram_Set: Command $cmd, no msg id specified";
}
Log3 $name, 5, "Telegram_Get $name: get message for id $arg";
# should return undef if succesful
$ret = Telegram_GetMessage( $hash, $arg );
}
Log3 $name, 5, "Telegram_Get $name: done with $ret: ";
return $ret
}
##############################
# attr function for setting fhem attributes for the device
sub Telegram_Attr(@) {
my ($cmd,$name,$aName,$aVal) = @_;
my $hash = $defs{$name};
Log3 $name, 5, "Telegram_Attr $name: called ";
return "\"Telegram_Attr: \" $name does not exist" if (!defined($hash));
Log3 $name, 5, "Telegram_Attr $name: $cmd on $aName to $aVal";
# $cmd can be "del" or "set"
# $name is device name
# aName and aVal are Attribute name and value
if ($cmd eq "set") {
if ($aName eq 'defaultPeer') {
$attr{$name}{'defaultPeer'} = $aVal;
} elsif ($aName eq 'defaultSecret') {
$attr{$name}{'defaultSecret'} = ($aVal eq "1")? "1": "0";
} elsif ($aName eq 'cmdKeyword') {
$attr{$name}{'cmdKeyword'} = $aVal;
} elsif ($aName eq 'cmdRestrictedPeer') {
$aVal =~ s/^\s+|\s+$//g;
# allow multiple peers with spaces separated
# $aVal =~ s/ /_/g;
$attr{$name}{'cmdRestrictedPeer'} = $aVal;
} elsif ($aName eq 'cmdTriggerOnly') {
$attr{$name}{'cmdTriggerOnly'} = ($aVal eq "1")? "1": "0";
} elsif ($aName eq 'cmdNumericIDs') {
$attr{$name}{'cmdNumericIDs'} = ($aVal eq "1")? "1": "0";
}
}
return undef;
}
#####################################
sub Telegram_Ready($)
{
my ($hash) = @_;
Log3 "tele", 5, "Telegram_Ready basic called ";
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_Ready $name: called ";
if($hash->{STATE} eq "disconnected") {
Log3 $name, 5, "Telegram $name: Telegram_Ready() state: disconnected -> DevIo_OpenDev";
return DevIo_OpenDev($hash, 1, "Telegram_DoInit");
}
return undef;
# return undef if( ! defined($hash->{REMAINING}) );
# return ( length($hash->{REMAINING}) );
}
#####################################
# _Read is called when data is available on the corresponding file descriptor
# data to be read must be collected in hash until the data is complete
# Parse only one message at a time to be able that readingsupdates will be sent out
# to be deleted
#ANSWER 65
#User First Last online (was online [2015/06/18 23:53:53])
#
#ANSWER 41
#55 [23:49] First Last >>> test 5
#
#ANSWER 66
#User First Last offline (was online [2015/06/18 23:49:08])
#
#mark_read First_Last
#ANSWER 8
#SUCCESS
#
#ANSWER 60
#806434894237732045 [16:51] !_First_Last »»» Aaaa
#
#ANSWER 52
#Secret chat !_First_Last updated access_hash
#
#ANSWER 57
# Encrypted chat !_First_Last is now in wait state
#
#ANSWER 47
#Secret chat !_First_Last updated status
#
#ANSWER 88
#-6434729167215684422 [16:50] !_First_Last First Last updated layer to 23
#
#ANSWER 63
#-9199163497208231286 [16:50] !_First_Last »»» Hallo
#
sub Telegram_Read($;$)
{
my ($hash, $noIO) = @_;
my $name = $hash->{NAME};
my $buf = '';
Log3 $name, 5, "Telegram_Read $name: called with noIo defined: ".defined($noIO);
# Read new data
if ( ! defined($noIO) ) {
$buf = DevIo_SimpleRead($hash);
if ( $buf ) {
Log3 $name, 5, "Telegram_Read $name: New read :$buf: ";
}
}
# append remaining content to buf
$hash->{REMAINING} = '' if( ! defined($hash->{REMAINING}) );
$buf = $hash->{REMAINING}.$buf;
$hash->{REMAINING} = $buf;
Log3 $name, 5, "Telegram_Read $name: Full buffer :$buf: ";
my ( $msg, $rawMsg );
# undefined return value as default
my $ret;
while ( length( $buf ) > 0 ) {
( $msg, $rawMsg, $buf ) = Telegram_getNextMessage( $hash, $buf );
if (length( $msg )>0) {
Log3 $name, 5, "Telegram_Read $name: parsed a message :".$msg.": ";
} else {
Log3 $name, 5, "Telegram_Read $name: parsed a raw message :".$rawMsg.": ";
}
# Log3 $name, 5, "Telegram_Read $name: and remaining :".$buf.": ";
# update REMAINING for recursion
$hash->{REMAINING} = $buf;
# Do we have a message found
if (length( $msg )>0) {
# Log3 $name, 5, "Telegram_Read $name: message in buffer :$msg:";
$hash->{lastmessage} = $msg;
#55 [23:49] First Last >>> test 5
# Ignore all none received messages // final \n is already removed
my ($mid, $mpeer, $mtext ) = Telegram_SplitMsg( $msg );
if ( defined( $mid ) ) {
Log3 $name, 5, "Telegram_Read $name: Found message $mid from $mpeer :$mtext:";
my $mpeernorm = $mpeer;
$mpeernorm =~ s/^\s+|\s+$//g;
$mpeernorm =~ s/ /_/g;
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "prevMsgId", $hash->{READINGS}{msgId}{VAL});
readingsBulkUpdate($hash, "prevMsgPeer", $hash->{READINGS}{msgPeer}{VAL});
readingsBulkUpdate($hash, "prevMsgText", $hash->{READINGS}{msgText}{VAL});
readingsBulkUpdate($hash, "msgId", $mid);
readingsBulkUpdate($hash, "msgPeer", $mpeernorm);
readingsBulkUpdate($hash, "msgText", $mtext);
readingsEndUpdate($hash, 1);
my $cmdRet = Telegram_ReadHandleCommand( $hash, $mpeernorm, $mtext );
if ( defined( $cmdRet ) ) {
$ret = "" if ( ! defined( $ret ) );
$ret .= $cmdRet;
}
}
}
}
return $ret;
}
##############################################################################
##############################################################################
##
## HELPER
##
##############################################################################
##############################################################################
#####################################
# INTERNAL: execute command and sent return value
sub Telegram_ReadHandleCommand($$$) {
my ($hash, $mpeernorm, $mtext ) = @_;
my $name = $hash->{NAME};
my $ret;
# command key word aus Attribut holen
my $ck = AttrVal($name,'cmdKeyword',undef);
return $ret if ( ! defined( $ck ) );
# trim whitespace from message text
$mtext =~ s/^\s+|\s+$//g;
return $ret if ( index($mtext,$ck) != 0 );
# OK, cmdKeyword was found / extract cmd
my $cmd = substr( $mtext, length($ck) );
# trim also cmd
$cmd =~ s/^\s+|\s+$//g;
Log3 $name, 5, "Telegram_ReadHandleCommand $name: cmd found :".$cmd.": ";
# validate security criteria for commands
if ( Telegram_checkAllowedPeer( $hash, $mpeernorm ) ) {
Log3 $name, 5, "Telegram_ReadHandleCommand cmd correct peer ";
# Either no peer defined or cmdpeer matches peer for message -> good to execute
my $cto = AttrVal($name,'cmdTriggerOnly',"0");
if ( $cto eq '1' ) {
$cmd = "trigger ".$cmd;
}
Log3 $name, 5, "Telegram_ReadHandleCommand final cmd for analyze :".$cmd.": ";
my $ret = AnalyzeCommand( undef, $cmd, "" );
Log3 $name, 5, "Telegram_ReadHandleCommand result for analyze :".$ret.": ";
if ( length( $ret) == 0 ) {
$ret = "telegram fhem ($mpeernorm) cmd :$cmd: result OK";
} else {
$ret = "telegram fhem ($mpeernorm) cmd :$cmd: result :$ret:";
}
Log3 $name, 5, "Telegram_ReadHandleCommand $name: cmd result :".$ret.": ";
# replace line ends with spaces
$ret =~ s/(\r|\n)/ /gm;
AnalyzeCommand( undef, "set $name message $mpeernorm: $ret", "" );
my $defpeer = AttrVal($name,'defaultPeer',undef);
if ( defined( $defpeer ) ) {
if ( Telegram_convertpeer( $defpeer ) ne $mpeernorm ) {
AnalyzeCommand( undef, "set $name messageTo $mpeernorm $ret", "" );
}
}
} else {
# unauthorized fhem cmd
Log3 $name, 1, "Telegram_ReadHandleCommand unauthorized cmd from user :$mpeernorm:";
$ret = "" if ( ! defined( $ret ) );
$ret .= "UNAUTHORIZED: telegram fhem cmd :$cmd: from user :$mpeernorm: \n";
}
return $ret;
}
#####################################
# INTERNAL: Check if peer is allowed - true if allowed
sub Telegram_checkAllowedPeer($$) {
my ($hash,$mpeer) = @_;
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_checkAllowedPeer $name: called with $mpeer";
my $cp = AttrVal($name,'cmdRestrictedPeer','');
return 1 if ( $cp eq '' );
my @peers = split( " ", $cp);
foreach my $cp (@peers) {
return 1 if ( $cp eq $mpeer );
}
return 0;
}
#####################################
# INTERNAL: split message into id peer and text
# returns id, peer, msgtext
sub Telegram_SplitMsg($)
{
my ( $msg ) = @_;
if ( $msg =~ /^(\d+)\s\[[^\]]+\]\s+([^\s][^>]*)\s>>>\s(.*)$/s ) {
return ( $1, $2, $3 );
} elsif ( $msg =~ /^(-?\d+)\s\[[^\]]+\]\s+!_([^»]*)\s\»»»\s(.*)$/s ) {
# secret chats have slightly different message format: can have a minus / !_ prefix on name and underscore between first and last / » instead of >
return ( $1, $2, $3 );
}
return undef;
}
#####################################
# INTERNAL: Initialize a connection to the telegram-cli
# requires to ensure commands are accepted / set this as main_session, get last msg id
sub Telegram_DoInit($)
{
my ( $hash ) = @_;
my $name = $hash->{NAME};
my $buf = '';
Log3 $name, 5, "Telegram_DoInit $name: called ";
# First needs send an empty line and read all returns away
$buf = Telegram_DoCommand( $hash, '', undef );
Log3 $name, 5, "Telegram_DoInit $name: Inital response is :".(defined($buf)?$buf:"undef").": ";
# Send "main_session" ==> returns empty
$buf = Telegram_DoCommand( $hash, 'main_session', '' );
Log3 $name, 5, "Telegram_DoInit $name: Response on main_session is :".(defined($buf)?$buf:"undef").": ";
return "DoInit failed on main_session with return :".(defined($buf)?$buf:"undef").":" if ( defined($buf) && ( length($buf) > 0 ));
# - handle initialization (client write / main session / read msg id and checks) in DoInit
$hash->{STATE} = "Initialized" if(!$hash->{STATE});
# ??? last message id and read all missing messages for default peer
$hash->{STATE} = "Ready" if(!$hash->{STATE});
return undef;
}
#####################################
# INTERNAL: Function to convert a peer name to a normalized form
sub Telegram_convertpeer($)
{
my ( $peer ) = @_;
my $peer2 = $peer;
$peer2 =~ s/^\s+|\s+$//g;
$peer2 =~ s/ /_/g;
return $peer2;
}
#####################################
# INTERNAL: Function to send a message or Phote to a peer and handle result
sub Telegram_SendIt($$$$)
{
my ( $hash, $peer, $msg, $isText) = @_;
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_SendIt $name: called ";
# trim and convert spaces in peer to underline
my $peer2 = Telegram_convertpeer( $peer );
my $defSec = AttrVal($name,'defaultSecret',0);
if ( $defSec ) {
$peer2 = "!_".$peer2;
$hash->{sentMsgSecure} = "secure";
} else {
$hash->{sentMsgSecure} = "normal";
}
my $cmd;
if ( $isText ) {
$hash->{sentMsgText} = $msg;
$cmd = "msg $peer2 $msg";
} else {
$hash->{sentMsgText} = "Photo: $msg";
$cmd = "send_photo $peer2 $msg";
}
$hash->{sentMsgPeer} = $peer2;
my $ret = Telegram_DoCommand( $hash, $cmd, "SUCCESS" );
if ( defined($ret) ) {
$hash->{sentMsgResult} = $ret;
} else {
$hash->{sentMsgResult} = "SUCCESS";
}
return $ret;
}
#####################################
# INTERNAL: Function to get the real name for a
sub Telegram_PeerToID($$)
{
my ( $hash, $peer ) = @_;
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_PeerToID $name: called ";
#????
return ;
}
#####################################
# INTERNAL: Function to get a message by id
sub Telegram_GetMessage($$)
{
my ( $hash, $msgid ) = @_;
my $name = $hash->{NAME};
Log3 $name, 5, "Telegram_GetMessage $name: called ";
my $cmd = "get_message $msgid";
return Telegram_DoCommand( $hash, $cmd, undef );
}
#####################################
# INTERNAL: Function to send a command handle result
# Parameter
# hash
# cmd - command line to be executed
# expect -
# undef - means no parsing of result - Everything is returned
# true - parse for SUCCESS = undef / FAIL: = msg
# false - expect nothing - so return undef if nothing got / FAIL: = return this
sub Telegram_DoCommand($$$)
{
my ( $hash, $cmd, $expect ) = @_;
my $name = $hash->{NAME};
my $buf = '';
Log3 $name, 5, "Telegram_DoCommand $name: called ";
Log3 $name, 5, "Telegram_DoCommand $name: send command :$cmd: ";
# Check for message in outstanding data from device
$hash->{REMAINING} = '' if( ! defined($hash->{REMAINING}) );
$buf = DevIo_SimpleReadWithTimeout($hash, 0.01);
if ( $buf ) {
Log3 $name, 5, "Telegram_DoCommand $name: Remaining read :$buf: ";
$hash->{REMAINING} .= $buf;
}
# Now write the message
DevIo_SimpleWrite($hash, $cmd."\n", 0);
Log3 $name, 5, "Telegram_DoCommand $name: send command DONE ";
$buf = DevIo_SimpleReadWithTimeout($hash, 0.5);
Log3 $name, 5, "Telegram_DoCommand $name: returned :".(defined($buf)?$buf:"undef").": ";
### Attention this might contain multiple messages - so split into separate messages and just check for failure or success
my ( $msg, $rawMsg, $retValue );
# ensure buf is defined for remaining processing (happens on startup)
$buf = '' if ( ! defined($buf) );
# Parse the different messages in the buffer
while ( length($buf) > 0 ) {
( $msg, $rawMsg, $buf ) = Telegram_getNextMessage( $hash, $buf );
Log3 $name, 5, "Telegram_DoCommand $name: parsed a message :".$msg.": ";
Log3 $name, 5, "Telegram_DoCommand $name: and rawMsg :".$rawMsg.": ";
Log3 $name, 5, "Telegram_DoCommand $name: and remaining :".$buf.": ";
# Return complete first rawmsg or $msg if nothing expected
if ( ! defined( $expect ) ) {
$hash->{REMAINING} .= $buf;
if ( length($msg) > 0 ) {
$retValue = $msg;
} else {
$retValue = $rawMsg;
}
last;
}
if ( length($msg) > 0 ) {
# Only FAIL / SUCCESS will be handled (and removed)
if ( $msg =~ /^FAIL:/ ) {
$retValue = $msg;
last;
} elsif ( $msg =~ /^SUCCESS$/s ) {
# reset $expect to make sure undef is returned
$expect = 0;
last;
} else {
$hash->{REMAINING} .= $rawMsg;
}
} else {
$retValue = $rawMsg;
last;
}
}
# add remaining buf to remaining for further operation
$hash->{REMAINING} .= $buf;
# handle remaining buffer
if ( length($hash->{REMAINING}) > 0 ) {
# call read with noIO set
Telegram_Read( $hash, 1 );
}
# Result is in retValue / expect might be reset if success is received
if ( defined( $retValue ) ) {
return $retValue;
} elsif ( $expect ) {
return "NO RESULT";
}
return undef;
}
#####################################