-
Notifications
You must be signed in to change notification settings - Fork 7
/
02_FHEMAPP.pm
1786 lines (1485 loc) · 50 KB
/
02_FHEMAPP.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: 02_FHEMAPP.pm 28679 2024-03-18 20:00:34Z Benni $
package FHEM::FHEMAPP;
use strict;
use warnings;
use HttpUtils;
use MIME::Base64;
use Data::Dumper;
use GPUtils qw(:all);
use File::Temp qw(tempfile tempdir cleanup);
use File::Path qw(rmtree);
#$dir = File::Temp->newdir();
#https://www.perl-howto.de/2008/07/temporare-dateien-sicher-erzeugen.html
#https://metacpan.org/release/TJENNESS/File-Temp-0.22/view/Temp.pm#OBJECT-ORIENTED_INTERFACE
#########################################################################
# Importing/Exporting Functions and variables from/to main
#########################################################################
BEGIN {
GP_Import(qw(
defs
data
AttrVal
ReadingsVal
InternalVal
Log3
fhem
readingFnAttributes
readingsSingleUpdate
readingsBeginUpdate
readingsBulkUpdateIfChanged
readingsBulkUpdate
readingsEndUpdate
readingsDelete
init_done
FW_CSRF
FW_confdir
FW_dir
FW_ME
CommandAttr
CommandDeleteAttr
devspec2array
getAllSets
getAllAttr
IsIgnored
unicodeEncoding
WriteStatefile
HttpUtils_NonblockingGet
getAllAttr
FileWrite
FileRead
FileDelete
gettimeofday
InternalTimer
RemoveInternalTimer
IsDisabled
deviceEvents
));
#Exporting Initialize for Main
GP_Export(qw(
Initialize
))
}
#########################################################################
# Trying to import functions from an applicaple JSON-Library
#########################################################################
my $JSON="none";
#JSON-Library-Usage was cpopied from Weather-APIs
# try to use JSON::MaybeXS wrapper
# for chance of better performance + open code
eval {
require JSON::MaybeXS;
import JSON::MaybeXS qw( decode_json encode_json );
$JSON='JSON::MaybeXS';
1;
} or do {
# try to use JSON wrapper
# for chance of better performance
eval {
# JSON preference order
local $ENV{PERL_JSON_BACKEND} =
'Cpanel::JSON::XS,JSON::XS,JSON::PP,JSON::backportPP'
unless ( defined( $ENV{PERL_JSON_BACKEND} ) );
require JSON;
import JSON qw( decode_json encode_json );
$JSON='JSON';
1;
} or do {
# In rare cases, Cpanel::JSON::XS may
# be installed but JSON|JSON::MaybeXS not ...
eval {
require Cpanel::JSON::XS;
import Cpanel::JSON::XS qw(decode_json encode_json);
$JSON='Cpanel::JSON::XS';
1;
} or do {
# In rare cases, JSON::XS may
# be installed but JSON not ...
eval {
require JSON::XS;
import JSON::XS qw(decode_json encode_json);
$JSON='JSON::XS';
1;
} or do {
# Fallback to built-in JSON which SHOULD
# be available since 5.014 ...
eval {
require JSON::PP;
import JSON::PP qw(decode_json encode_json);
$JSON='JSON::PP';
1;
} or do {
# Fallback to JSON::backportPP in really rare cases
require JSON::backportPP;
import JSON::backportPP qw(decode_json encode_json);
$JSON='JSON::backportPP';
1;
};
};
};
};
};
#########################################################################
# Constants and defaults
#########################################################################
use constant {
FA_VERSION => '1.1.0', #Version of this Modul
FA_VERSION_FILENAME => 'CHANGELOG.md', #Default Version Filename
FA_INIT_INTERVAL => 60, #Default Startup Interval
FA_DEFAULT_INTERVAL => 3600, #Default Interval
FA_GITHUB_URL => 'https://github.com/jemu75/fhemApp',
FA_GITHUB_API_BASEURL => 'https://api.github.com/repos/jemu75/fhemApp',
FA_GITHUB_API_OWNER => 'jemu75',
FA_GITHUB_API_REPO => 'fhemApp',
FA_GITHUB_API_RELEASES => 'releases',
FA_TAR_SUB_FOLDER => 'www/fhemapp4',
FA_VERSION_LOWEST => '4.0.0',
FA_MOD_TYPE => (split('::',__PACKAGE__))[-1],
INT_SOURCE_URL => 'SOURCE_URL', #INTERNAL NAME
INT_CONFIG_FILE => 'CONFIG_FILE', #INTERNAL NAME
INT_INTERVAL => 'INTERVAL', #INTERNAL NAME
INT_VERSION => 'VERSION', #INTERNAL NAME
INT_JSON_LIB => '.JSON_LIB', #INTERNAL NAME
INT_LOCAL_INST => 'LOCAL', #INTERNAL NAME
INT_PATH => 'PATH', #INTERNAL NAME
INT_LINK => 'FHEMAPP_UI', #INTERNAL NAME
INT_FANAME => 'FHEMAPP_NAME' #INTERNAL NAME
};
no warnings 'qw';
my @attrList = qw(
disable:1,toggle
interval
sourceUrl
updatePath:beta
exposeConfigFile:1
linkPath
);
# autoUpdate:1
use warnings 'qw';
#########################################################################
# FHEM - Module management Functions (xxxFn)
#########################################################################
#========================================================================
sub Initialize
#========================================================================
{
my $hash=shift // return;
$hash->{DefFn} = \&Define;
$hash->{GetFn} = \&Get;
$hash->{SetFn} = \&Set;
$hash->{DeleteFn} = \&Delete;
$hash->{CopyFn} = \&DeviceCopied;
$hash->{RenameFn} = \&DeviceRenamed;
$hash->{NotifyFn} = \&Notify;
$hash->{AttrFn} = \&Attr;
$hash->{AttrList} = join(" ", @attrList)." $readingFnAttributes";
}
#========================================================================
sub Attr # AttrFn
#========================================================================
{
my $cmd= shift // return undef;
my $name=shift // return undef;
my $att= shift // return undef;
my $val= shift;
my $hash = $defs{$name};
#set fa interval 59
Log($name,"AttrFn: $cmd $name $att $val",4);
if($att eq 'disable') {
if($val && $val==1) {
StopLoop($hash);
readingsSingleUpdate($hash,'state','disabled',1);
}
elsif ( $cmd eq "del" or !$val ) {
readingsSingleUpdate($hash,'state','defined',1);
StartLoop($hash,FA_INIT_INTERVAL,0,1);
}
}
elsif($att eq 'interval') {
if($cmd eq 'set') {
$val+=0;
if($val < FA_INIT_INTERVAL) {
$val=0;
#will be disabled if < 60 seconds => set to 0
return "$att should not be set lower than ".FA_INIT_INTERVAL;
}
elsif($val > 86400) {
return "$att should not be longer than 1 day (86400 sec)";
}
elsif($val==FA_DEFAULT_INTERVAL) {
return "Default for $att is already $val";
}
$hash->{&INT_INTERVAL}=$val;
StartLoop($hash,FA_INIT_INTERVAL,1);
}
else
{
$hash->{&INT_INTERVAL}=FA_DEFAULT_INTERVAL;
StartLoop($hash,FA_INIT_INTERVAL,1);
}
}
elsif($att eq 'sourceUrl') {
if($cmd eq 'set') {
if($val eq FA_GITHUB_URL) {
return "$val is already default for $att";
}
$hash->{&INT_SOURCE_URL}=$val;
}
else
{
$hash->{&INT_SOURCE_URL}=FA_GITHUB_URL;
}
}
elsif($att eq 'exposeConfigFile') {
my $filespec=get_config_file($name,undef,1);
if($cmd eq 'set') {
if($val) {
if(int($val) != 1) {
return "$val is not valid for $att";
}
Log($name,"$att changed to $val!",4);
$data{confFiles}{$filespec} = '0';
}
} else {
Log($name,"$att was deleted!",4);
delete($data{confFiles}{$filespec});
}
} elsif($att eq 'linkPath') {
if($cmd eq "set") {
set_fhemapp_link($hash,$val);
} else {
set_fhemapp_link($hash,'%%DELETE%%');
}
}
return undef;
}
#========================================================================
sub Notify # NofifyFn
#========================================================================
{
my $hash = shift // return;
my $src_hash=shift // return;
my $name = $hash->{NAME};
return if(IsDisabled($name));
my $src = $src_hash->{NAME};
my $events = deviceEvents($src_hash,1);
return if( !$events );
#HANDLING GLOBAL EVENTS
if($src eq 'global') {
foreach my $event (@{$events}) {
Log($name,"EVENT: $src:$event",5);
$event = "" if(!defined($event));
if($event eq 'INITIALIZED') {
Log($name,"Event recieved from '$src'",5);
StartLoop($hash,FA_INIT_INTERVAL);
}
}
}
return;
}
#========================================================================
sub Define # DefFn
#========================================================================
{
my $hash=shift // return;
my $def=shift;
my @a = split("[ \t][ \t]*", $def);
my $name=shift @a;
my $type=shift @a;
my $fa_name= shift @a;
Log(undef,"DefFn called for $name $init_done",4);
#Setting INTERNAL values
$hash->{&INT_VERSION}=FA_VERSION;
$hash->{&INT_SOURCE_URL}=AttrVal($name,'sourceUrl',FA_GITHUB_URL);
$hash->{&INT_JSON_LIB}=$JSON;
$hash->{&INT_CONFIG_FILE}=get_config_file($name);
$hash->{&INT_INTERVAL}=AttrVal($name,'interval',FA_DEFAULT_INTERVAL);
$hash->{&INT_FANAME}=$fa_name;
$hash->{NOTIFYDEV}="global";
#Internal PATH is only available if local path is specified in DEF
if($fa_name eq 'none') {
delete($hash->{&INT_PATH});
$hash->{&INT_LOCAL_INST}=0;
} else {
$hash->{&INT_PATH}="$FW_dir/$fa_name";
$hash->{&INT_LOCAL_INST}=1;
}
set_fhemapp_link($hash);
#Setting defined state
if(!$init_done) {
#Reading conifg on Define, e.g. when copied from other device
#[todo]: this is not necessary on simple define .... Move to CopyFn?
ReadConfig($hash);
}
else
{
#Start Version loop
#[todo]: maybe move to global:Initialize handling in NotifyFn
StartLoop($hash,FA_INIT_INTERVAL);
}
#Set startup disabled/defined state
if(IsDisabled($name)) {
readingsSingleUpdate($hash,'state','disabled',0);
}
else
{
readingsSingleUpdate($hash,'state','defined',0);
}
#AddExtension( $name, \&ExtensionGetConfigData, FA_MOD_TYPE . "/$name/cfg" );
return "Wrong syntax: use define <name> fhemapp <localFhemappPath|none>" if(!$fa_name);
}
#========================================================================
sub Get # GetFn
#========================================================================
{
my $hash=shift // return;
my $name=shift;
my $opt=shift;
return "\"get $name\" needs at least one argument" unless(defined($opt));
my $localInst=InternalVal($name,INT_LOCAL_INST,0);
if($opt eq 'config') {
return encode_base64(get_config($hash));
}
elsif($opt eq 'rawconfig') {
return get_config($hash);
}
elsif($opt eq 'options') {
return AttrOptions_json($name);
}
elsif($opt eq 'version') {
if($localInst) {
check_local_version($hash);
return ReadingsVal($name,'local_version','unknown');
#return get_local_version($hash);
}
return "not available!";
}
elsif($opt eq 'localfolder') {
if($localInst) {
return get_local_path($hash);
}
return "not available!"
}
else
{
#my $loc_gets='version:noArg';
my $loc_gets='version:noArg';
if($localInst) {
return "Unknown argument $opt, choose one of rawconfig:noArg $loc_gets";
} else {
return "Unknown argument $opt, choose one of rawconfig:noArg";
}
}
}
#========================================================================
sub Set # SetFn
#========================================================================
{
my $hash=shift // return;
my $name=shift;
my $opt=shift;
my @args=@_;
my $localInst=InternalVal($name,INT_LOCAL_INST,0);
return "\"set $name\" needs at least one argument" unless(defined($opt));
if($opt eq 'config') {
set_config($hash,decode_base64(join(" ",@args)),1);
}
elsif($opt eq 'rawconfig') {
set_config($hash,join(" ",@args),1);
}
elsif($opt eq 'update') {
if($localInst) {
update($hash);
} else {
return "$opt not available for " . FA_MOD_TYPE . " without local fhemapp path!";
}
}
elsif($opt eq 'getConfig') {
return get_config($hash);
}
#elsif($opt eq 'forceVersion') {
#return forceVersion($hash,@args);
#}
elsif($opt eq "checkVersions") {
if($localInst) {
check_local_version($hash);
Request_Releases($hash)
} else {
return "$opt not available for " . FA_MOD_TYPE . " without local fhemapp path!";
}
}
elsif($opt eq "createfolder") {
create_fhemapp_folder($hash);
}
elsif($opt eq "refreshLink") {
set_fhemapp_link($hash);
}
elsif($opt eq "rereadCfg") {
ReadConfig($hash,1);
}
else {
if($localInst) {
return "Unknown argument $opt, choose one of getConfig:noArg checkVersions:noArg update:noArg rereadCfg:noArg";
} else {
return "Unknown argument $opt, choose one of getConfig:noArg rereadCfg:noArg";
}
}
return undef;
}
#========================================================================
sub Delete # DeleteFn
#========================================================================
#Cleanup when device is deleted
{
my $hash=shift // return;
#Cancel and delete runnint internal timer
StopLoop($hash);
#Delete config file
DeleteConfig($hash);
}
#========================================================================
sub DeviceCopied #CopyFn
#========================================================================
{
my $old_name=shift // return;
my $new_name=shift // return;
Log ($new_name,"Copying config '$old_name' -> '$new_name'",4);
$defs{$new_name}{helper}{config} = $defs{$old_name}{helper}{config};
#Log($new_name,$new_hash->{helper}{config},5);
WriteConfig($defs{$new_name});
return;
}
#========================================================================
sub DeviceRenamed #RenameFn
#========================================================================
{
my $new_name=shift // return;
my $old_name=shift // return;
Log($new_name,"Device renamed '$old_name' -> '$new_name'",4);
my $new_hash=$defs{$new_name};
WriteConfig($new_hash);
my $oldFile=get_config_file($old_name);
Log($new_name,"Deleting config '$oldFile' ...",4);
FileDelete($oldFile);
return;
}
#========================================================================
sub ExtensionGetConfigData
#========================================================================
{
my ($request) = @_;
my $TP=FA_MOD_TYPE;
#Log($TP,"$TP got WebRequest: $request",2);
if ( $request =~ /^\/$TP\/(\w+)\/cfg/x ) {
my $name = $1;
my $dta=$defs{$name}{helper}{config};
return ( "application/json", $dta );
#return ( "text/plain; charset=utf-8",
#"you've successfully reached a $TP device ($name) for webhook $request in " . __PACKAGE__ );
}
return ( "text/plain; charset=utf-8",
"No $TP device for webhook $request" );
}
#========================================================================
sub AddExtension
#========================================================================
{
my ( $name, $func, $link ) = @_;
my $url = "/$link";
Log( $name, "Registering " . FA_MOD_TYPE . " $name for URL $url",3 );
$::data{FWEXT}{$url}{deviceName} = $name;
$::data{FWEXT}{$url}{FUNC} = $func;
$::data{FWEXT}{$url}{LINK} = $link;
return;
}
#========================================================================
sub RemoveExtension
#========================================================================
{
my ($link) = @_;
my $url = "/$link";
my $name = $::data{FWEXT}{$url}{deviceName};
Log( $name, "Unregistering " . FA_MOD_TYPE . " $name for URL $url",3 );
delete $::data{FWEXT}{$url};
return;
}
#========================================================================
sub create_fhemapp_folder
#========================================================================
{
my $hash=shift // return;
my $name=$hash->{NAME};
my $localInst=InternalVal($name,INT_LOCAL_INST,0);
if(!$localInst) {
Log($name,"create_fhemapp_folder: no local fhemapp-instance!",2);
return 0;
}
my $fld=InternalVal($name,INT_PATH,undef);
if(!$fld) {
Log($name,"no path specification found check DEF of $name",2);
return 0;
}
if(-d $fld) {
Log($name,"create_fhemapp_folder: folder already exists: '$fld'",2);
return 0;
}
mkdir($fld);
if(-d $fld) {
Log($name,"create_fhemapp_folder: folder successfully created: '$fld'",4);
return 1;
} else {
Log($name,"create_chemapp_folder: unable to create folder '$fld'",2);
return 0;
}
#my $name=shift // return;
#my $destFolder=InternalVal($name,INT_PATH,'none');
}
#========================================================================
sub forceVersion
#========================================================================
{
my $hash=shift // return 'no hash';
my @args=shift // return 'no args';
my $first=shift @args // return 'empty args';
my $name=$hash->{NAME};
my $localPath=get_local_path($hash);
return "$first - $localPath";
}
#========================================================================
sub update {
#========================================================================
my $hash=shift // return;
my $name = $hash->{NAME};
my $continueUpdate = shift;
$continueUpdate //=0;
#TODO: Get Releases ... this is a non-blocking (async) process ...
# ... need to wait until finished ... non-blocking :(
if(!$continueUpdate) {
Log($name,"Update ... first checking versions ...",4);
check_local_version($hash);
Request_Releases($hash,1);
return;
} else {
Log($name,"Update ... got releases ... continuing...",4);
}
#Find required tarball-URL
my $url=undef;
my $updatePath=AttrVal($name,'updatePath','stable');
if( $updatePath eq 'beta') {
$url=ReadingsVal($name,'.pre_tarball_url',undef);
} else {
$url=ReadingsVal($name,'.stable_tarball_url',undef);
}
#Build non-blocking request to download tarball from github
#Donwload is handled in callback sub 'update_response'
if($url) {
Log($name,"Requesting: $url",4);
my $param = {
url => $url,
timeout => 5,
hash => $hash,
method => "GET",
header => "User-Agent: TeleHeater/2.2.3\r\nAccept: application/json",
callback => \&update_response
};
HttpUtils_NonblockingGet($param);
} else {
Log($name, "Update: No url for current update-path '$updatePath' available!",4);
}
return;
}
#========================================================================
sub update_response{
#========================================================================
my ($param, $err, $data) = @_;
my $hash = $param->{hash};
my $name = $hash->{NAME};
my $localPath=get_local_path($hash);
my $fname="fhemapp_update.tar.gz";
Log($name,"request-header: ".$param->{httpheader},5);
#Extracting the package filename from httpheader
if($param->{httpheader} =~/filename=(.+.tar.gz)/gm) {
$fname=$1;
}
Log($name,"filename for update package is $fname");
#{my $v1="ertuy";;if($v1 =~ /er(tu)y/gm) {$1}}
my @hdr=split('\n',$param->{httpheader});
Log($name,"http-header:".Dumper(@hdr),5);
if($err ne "")
{
#An Error occured during request
Log($name,"error while requesting ".$param->{url}." - $err",4);
readingsSingleUpdate($hash, ".fullResponse", "ERROR: $err", 0);
}
elsif($data ne "")
{
#Incoming data ... saving file
Log($name,"update data recieved ".$param->{url},4);
my $dir = tempdir(CLEANUP=>1);
$dir=~ s!/*$!/!;
my $filename="${dir}$fname";
my @content;
push @content,$data;
#FileWrite($filename,@content); #-> Added one, unwanted character (probably a \n)
#So doing "native" file-write here:
Log($name,"writing $filename ",4);
open(FH, '>', $filename);
print FH $data;
close(FH);
#my $topfolder=`tar -tzf $filename' | head -1 | cut -f1 -d"/"`;
#chomp $topfolder;
my $tarlist=`tar -tzf $filename`;
my $topfolder=(split /\n/, $tarlist )[0];
chop $topfolder if($topfolder =~ /.*\/$/);
Log($name,"top folder in '$filename' is $topfolder");
if(!$topfolder) {
Log($name, "Unable to get top folder from '$filename'",4);
temp_cleanup($hash);
return;
}
my $fullTarFolder="$topfolder/".FA_TAR_SUB_FOLDER;
my $depth=scalar(split("/",$fullTarFolder));
my $lpath=get_local_path($hash);
my $bpath=undef;
if($lpath) {
Log($name,"Local path already exists: '$lpath'",4);
$bpath="$lpath.bak";
#TODO: Do not remove --> should introduce a force variant
if($bpath && -d $bpath) {
Log($name,"Trying to remove previously left backup folder '$bpath'",3);
my $res=rmtree($bpath,0,1);
}
Log($name,"-> renaming to '$bpath'",4);
if(!rename($lpath,$bpath)) {
Log($name,"Error renaming folder '$lpath' to '$bpath'",2);
temp_cleanup($hash);
return;
}
}
if(!$lpath || ! -d $lpath) {
if(create_fhemapp_folder($hash)) {
$lpath=get_local_path($hash);
my $cmd="tar xf $filename -C $lpath $topfolder/". FA_TAR_SUB_FOLDER . " --strip-components $depth";
Log($name,"extract cmd '$cmd' ",4);
my $res=system($cmd);
Log($name,"extract result: $res",4);
}
} else {
Log($name, "Local path still exists (shouldn't): '$lpath'",2);
temp_cleanup($hash);
return;
}
#Trying to cleanup temp-folder ...
temp_cleanup($hash);
#Updating local version (Readings)
if($bpath && -d $bpath) {
Log($name,"Removing backup folder '$bpath' after sucessfull installlation",4);
my $res=rmtree($bpath,0,1);
}
check_local_version($hash);
check_update_available($hash);
}
return;
}
#========================================================================
sub temp_cleanup{
#========================================================================
my $hash=shift // return;
my $name=$hash->{NAME};
if(cleanup()==0) {
Log($name,"Successfully cleaned temp folder",4);
} else {
Log($name,"Cleanup of temp folder failed!",2)
}
}
#========================================================================
sub Request_Releases
#========================================================================
{
my $hash=shift // return;
my $name = $hash->{NAME};
my $continueUpdate=shift;
$continueUpdate //= 0;
my $url=AttrVal($name,'sourceUrl',FA_GITHUB_API_BASEURL);
$url=~ s!/*$!/!;
$url.=FA_GITHUB_API_RELEASES;
Log($name,"Requesting: $url",4);
my $param = {
url => $url,
timeout => 5,
hash => $hash,
method => "GET",
header => "User-Agent: TeleHeater/2.2.3\r\nAccept: application/json",
callback => \&Request_Releases_Response,
continueUpdate => $continueUpdate
};
HttpUtils_NonblockingGet($param);
return;
}
#========================================================================
sub Request_Releases_Response($)
#========================================================================
{
my ($param, $err, $data) = @_;
my $hash = $param->{hash};
my $name = $hash->{NAME};
if($err ne "")
{
Log($name,"error while requesting ".$param->{url}." - $err",5);
#readingsSingleUpdate($hash, ".fullResponse", "ERROR: $err", 0);
}
elsif($data ne "")
{
Log($name,"url ".$param->{url}." returned: $data",5);
#Log3 $name, 3, Dumper $data;
my $rels = decode_json($data);
my $latestPre=undef;
my $latestFull=undef;
foreach my $rel (@{$rels}){
Log($name,"Release: " . $rel->{tag_name},5);
my $isVer=version_compare($rel->{tag_name},FA_VERSION_LOWEST);
Log($name,"Lowest: " . FA_VERSION_LOWEST . " is: $isVer",5);
if($isVer < 0) {
next;
}
if( !$latestPre && $rel->{prerelease}) {
$latestPre=$rel;
}
if(!$latestFull && !$rel->{prerelease}) {
$latestFull=$rel;
}
}
my $updateAvailable=0;
my $updatePath=AttrVal($name,'updatePath','stable');
#Updating device readings
readingsBeginUpdate($hash);
readingsBulkUpdateIfChanged($hash,'.latest_url',$param->{url},0);
if($latestPre) {
Log($name,"Latest-Pre: " . $latestPre->{tag_name},4);
readingsBulkUpdateIfChanged($hash,'pre_tag_name',$latestPre->{tag_name},1);
readingsBulkUpdateIfChanged($hash,'pre_html_url',$latestPre->{html_url},1);
readingsBulkUpdateIfChanged($hash,'.pre_tarball_url',$latestPre->{tarball_url},0);
readingsBulkUpdateIfChanged($hash,'pre_info',$latestPre->{body},1);
readingsBulkUpdateIfChanged($hash,'pre_published_at',$latestPre->{published_at},1);
} else {
readingsBulkUpdateIfChanged($hash,'pre_tag_name','unknown',1);
}
if($latestFull) {
Log($name,"Latest-Stable: " . $latestFull->{tag_name},4);
readingsBulkUpdateIfChanged($hash,'stable_tag_name',$latestFull->{tag_name},1);
readingsBulkUpdateIfChanged($hash,'stable_html_url',$latestFull->{html_url},1);
readingsBulkUpdateIfChanged($hash,'.stable_tarball_url',$latestFull->{tarball_url},0);
readingsBulkUpdateIfChanged($hash,'stable_info',$latestFull->{body},1);
readingsBulkUpdateIfChanged($hash,'stable_published_at',$latestFull->{published_at},1);
} else {
readingsBulkUpdateIfChanged($hash,'stable_tag_name','unknown',1);
}
#In case of error ....
#readingsBulkUpdate($hash, ".fullResponse", $data,0);
if($err) {
readingsBulkUpdateIfChanged($hash,'request_result','error',1);
readingsBulkUpdate($hash,'request_error',$err,1);
} else {
readingsBulkUpdateIfChanged($hash,'request_result','success',1);
}
readingsEndUpdate($hash,1);
#Delete un-fillable version information readings
if(!$latestPre) {
readingsDelete($hash,'pre_html_url');
readingsDelete($hash,'.pre_tarball_url');
readingsDelete($hash,'pre_info');
readingsDelete($hash,'pre_published_at');
}
if(!$latestFull) {
readingsDelete($hash,'stable_html_url');
readingsDelete($hash,'.stable_tarball_url');
readingsDelete($hash,'stable_info');
readingsDelete($hash,'stable_published_at');
}
if(!$err) {
readingsDelete($hash,'request_error');
}
}
if($param->{continueUpdate}) {
#if called during update process ... continue with update
update($hash,1);
} else {
check_update_available($hash);
}
}
#========================================================================
sub check_update_available
#========================================================================
{
my $hash=shift // return;
my $name=$hash->{NAME};
my $path=AttrVal($name,'updatePath','stable');
my $ver=ReadingsVal($name,'stable_tag_name','unknown');
$ver=ReadingsVal($name,'pre_tag_name','unknown') if($path eq "beta");
return if($ver eq 'unknown');
my $local_ver=ReadingsVal($name,'local_version','unknown');
if ($local_ver eq 'unknown' || version_compare($ver,$local_ver) ) {
readingsSingleUpdate($hash,'update_available',1,1);
} else {
if(ReadingsVal($name,'update_available',undef) ne '0') {
readingsSingleUpdate($hash,'update_available','0',1);
}
}
}
#========================================================================
sub set_fhemapp_link {
#========================================================================
my $hash=shift // return;
my $forceValue=shift;
my $name=$hash->{NAME};
#my $fa_name=$hash->{&INT_FANAME};
my $fw_me=$FW_ME;
$fw_me //= '/fhem';
my $fa_name=AttrVal($name,'linkPath',undef);
$fa_name=$hash->{&INT_FANAME} if($hash->{&INT_LOCAL_INST});
if($forceValue) {
if($forceValue ne '%%DELETE%%') {
$fa_name=$forceValue;
} else {
$fa_name=undef;
}