-
Notifications
You must be signed in to change notification settings - Fork 4
/
TMsStrava.pm
1473 lines (1287 loc) · 49.2 KB
/
TMsStrava.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
package TMsStrava;
# by Torben Menke https://entorb.net
# DESCRIPTION
# Package for Strava app
# Modules: My Default Set
use strict;
use warnings;
use 5.010; # say
use Data::Dumper;
use utf8; # this script is written in UTF-8
binmode STDOUT, ':utf8'; # default encoding for linux print STDOUT
use autodie qw (open close)
; # Replace functions with ones that succeed or die: e.g. close
# use local::lib; # at entorb.net some modules require use local::lib!!!
use lib ('/var/www/virtual/entorb/perl5/lib/perl5');
# Modules: Perl Standard
use Encode qw(encode decode);
use File::Basename; # for basename, dirname, fileparse
use File::Path qw(make_path remove_tree);
use Exporter qw(import)
; # gives you Exporter's import() method directly -> use for exporting variables via our @EXPORT
our @EXPORT
= qw( %o %s); # o = Global Settings / Options ; s = Session variables
# use parent 'Exporter'; # imports and subclasses Exporter
# our @EXPORT = qw($var); # put stuff here you want to export
# put vars into @EXPORT_OK that will be exported on request
use Time::HiRes('time'); # -> time() -> float of seconds
use Time::Local; # date vars -> timestamp
use Storable; # read and write variables to
# Modules: CPAN
use LWP::UserAgent; # http requests
use JSON; # imports encode_json, decode_json, to_json and from_json.
# important: install JSON::XS as well, as JSON uses it, if present, and it is MUCH faster
our %o; # Global Settings / Options, is exported, see above
our %s; # Session variables, is exported, see above
$o{'dataFolderBase'} = '/var/www/virtual/entorb/data-web-pages/strava';
$o{'tmpDataFolderBase'} = $o{'dataFolderBase'} . '/tmp';
$o{'tmpDownloadFolderBase'} = './download';
$o{'dirKnownLocationsBase'} = $o{'dataFolderBase'} . '/knownLocations';
$o{'ageDeleteOldDataFolders'} = 7200; # s
$o{'urlStravaAPI'} = "https://www.strava.com/api/v3";
$o{'cityGeoDatabase'} = $o{'dataFolderBase'} . '/city-gps.dat';
$s{'tsStart'} = time; # timestamp of start
# TODO: logging enable/disable
$s{'write-session-log'} = 1; # Write session logfile
# tmpDataFolder and tmpDownloadFolder are set after session is known
# $s{'tmpDataFolder'}; # is set later the session is appended
# $s{'tmpDownloadFolder'}; # later the session is appended
use constant PI => 4 * atan2( 1, 1 );
sub whoAmI {
# fetch athlete info from strava
# in: Token
# out: UserID, Username
my ($token) = @_;
logSubStart('whoAmI');
my $cont = getContfromURL( "$o{'urlStravaAPI'}/athlete", $token );
my %h = convertJSONcont2Hash($cont);
return ( $h{'id'} + 0, $h{'username'} );
} ## end sub whoAmI
sub logIt {
# append to sessionlogfile, with is overwritten for each website action
# in: $str to append to logfile, only if $s{'FhSessionLog'} == is set
# out: nothing
my ($string) = @_;
# logSubStart ('logIt');
if ( my $fh = $s{'FhSessionLog'} ) { # only if session logging is enabled
$_ = sprintf '%.1fs', ( time - $s{'tsStart'} );
say {$fh} $_ . "\t" . $string;
}
return;
} ## end sub logIt
sub logSubStart {
# logs the start of a sub / method
# in: $str to pass to log ( in log the check if $s{'write-session-log'} == 1 is performed)
my ($str) = @_;
# logSubStart ('logIt');
logIt("=== start of sub: $str ===");
return;
} ## end sub logSubStart
sub initSessionVariables {
# validates $session
# read stored session.txt from "$o{'tmpDataFolderBase'}/$session/session.txt"
# sets $s{'tmpDataFolder'} and $s{'tmpDownloadFolder'}
# in: $session
# out : nothing
# former out: Array of ($stravaUserID,$stravaUsername,$token,$scope)
my ($session) = @_;
# $session = 'cGjopr0eSVOVXC9_JJOW2A' ; ##TODO: set session for run via terminal
logSubStart('initSessionVariables');
logIt("session = '$session'");
if ( $session eq '' ) {
die "ERROR: bad session '$session'";
}
if ( not $session =~ m/^[a-zA-Z0-9_\-]+$/ ) {
die "ERROR: bad session '$session'";
}
$s{'session'} = $session;
$s{'tmpDataFolder'} = "$o{'tmpDataFolderBase'}/$session";
$s{'tmpDownloadFolder'} = "$o{'tmpDownloadFolderBase'}/$session";
$s{'pathToActivityListHashDump'}
= "$s{'tmpDataFolder'}/activityList/activityList-Array.dmp";
$s{'pathToActivityListJsonDump'}
= "$o{'tmpDownloadFolderBase'}/$session/activityList.json";
$s{'pathToGearHashDump'} = "$s{'tmpDataFolder'}/gear.dmp";
$s{'pathToClubsHashDump'} = "$s{'tmpDataFolder'}/clubs.dmp";
# update timestamp of temp dir to extent session expire date
system( "touch", $s{'tmpDataFolder'} );
my $fileIn = "$s{'tmpDataFolder'}/session.txt";
if ( not -f $fileIn ) {
say
"Uops, it seems your session '$session' has expired. Please start a <a href=\"./index.html\">new session</a>.";
exit;
}
# say $fileIn and die;
open my $fhIn, '<', $fileIn or die "ERROR: bad session '$session'";
my @cont = <$fhIn>;
close $fhIn;
chomp @cont; # remove spaces
if ( $s{'write-session-log'} == 1 ) {
my $fileLog = "$s{'tmpDataFolder'}/log-session.log";
open my $fhIn, '>>', $fileLog
or die "ERROR: can't write to session logfile'";
print {$fhIn} "\n\n\n\n";
$s{'FhSessionLog'} = $fhIn;
# not closed: not nice, but makes life easier...
} ## end if ( $s{'write-session-log'...})
# check stored user ID vs. user ID via Strava API
# not needed
# my ($stravaUserID2, $stravaUsername2) = TMsStrava::whoAmI($token);
# if ($stravaUserID2 ne $stravaUserID or $stravaUsername2 ne $stravaUsername) {
# die("ERROR: bad session");
# }
( $s{'stravaUserID'}, $s{'stravaUsername'}, $s{'token'}, $s{'scope'} )
= @cont;
$s{'fileKnownLocations'}
= "$o{'dirKnownLocationsBase'}/$s{'stravaUserID'}.txt";
# return @cont; # ($stravaUserID,$stravaUsername,$token,$scope) # not used any more, now this is stored in %s
return;
} ## end sub initSessionVariables
sub clearDownload {
logSubStart('clearDownload');
unlink foreach (<$s{'tmpDownloadFolder'}/*.ics>);
unlink foreach (<$s{'tmpDownloadFolder'}/*.json>);
unlink foreach (<$s{'tmpDownloadFolder'}/*.xlsx>);
unlink foreach (<$s{'tmpDownloadFolder'}/*.zip>);
return;
} ## end sub clearDownload
sub clearCache {
logSubStart('clearCache');
# after modification I cleanup this session's downloaded activity list jsons and stored dump files, since they are not up to date any more
unlink foreach (<$s{'tmpDataFolder'}/activityList/*.json>); #
unlink foreach (<$s{'tmpDataFolder'}/activityList/*.dmp>);
clearDownload();
# unlink foreach (<$s{'tmpDataFolder'}/activitySingle/*.json>); # TODO after implementing single activity json download
return;
} ## end sub clearCache
sub deauthorize {
my ( $token, $silent ) = @_;
# in: token, silent [0,1] (1-> do not die on error)
# out: nothing
logSubStart('deauthorize');
my ( $htmlcode, $cont )
= PostPutJsonToURL( 'POST', "https://www.strava.com/oauth/deauthorize",
$token, $silent );
# my %h = convertJSONcont2Hash($cont);
return;
} ## end sub deauthorize
sub fetchActivitySingle {
# fetch detailed activity, store JSON in file system
# IDEA: change filename to ID only? For better web access? Advantage of date first is sort order...
# output location: "$s{'tmpDataFolder'}/activitySingle/" . $date . "-" . $h{"type"} . "-$id" . ".json";
# in: $token, $id of activity, $txt [0,1] -> 1 generates .txt files from the jsons
my ( $token, $id, $txt ) = @_;
logSubStart('fetchActivitySingle');
my $cont = getContfromURL(
"$o{'urlStravaAPI'}/activities/$id?include_all_efforts=true", $token );
my %h = convertJSONcont2Hash($cont);
my $date = $h{"start_date_local"}; # 2018-08-21T08:14:53Z
$date =~ m/^(\d{4})\-(\d{2})\-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/
or die "E: activity date '$date' not matching '2018-08-21T08:14:53Z'";
$date = "$1$2$3-$4$5";
# my $fileOut = "activities/activity.json";
my $fileOut
= "$s{'tmpDataFolder'}/activitySingle/"
. $date . "-"
. $h{"type"} . "-$id" . ".json";
$_ = dirname($fileOut);
make_path $_ unless -d $_;
open my $fhOut, '>:encoding(UTF-8)', $fileOut
or die("ERROR: Can't write to file '$fileOut': $!");
print {$fhOut} $cont;
close $fhOut;
# .txt output
if ( $txt == 1 ) {
$fileOut =~ s/\.json$/.txt/;
open $fhOut, '>:encoding(UTF-8)', $fileOut
or die("ERROR: Can't write to file '$fileOut': $!");
foreach my $k ( sort keys %h ) {
next if ( not defined $h{$k} );
my $s = $h{$k};
$s = ref2String($s);
print {$fhOut} "$k\t: $s\n";
} ## end foreach my $k ( sort keys %h)
close $fhOut;
} ## end if ( $txt == 1 )
return;
} ## end sub fetchActivitySingle
sub getContfromURL {
# retrieve content from url, using HTTP GET
# in: $url, $token
# returns string of contents
my ( $url, $token ) = @_; # () important!!!
logSubStart('getContfromURL');
logIt("url='$url'");
my $req = HTTP::Request->new( GET => $url );
$req->header( 'Accept' => 'application/json' );
$req->header( 'Accept-Encoding' => 'UTF-8' );
$req->header( 'Authorization' => "Bearer $token" );
# creat User Agent using LWP
my $ua = LWP::UserAgent->new();
# TODO: App Name
# $ua->agent("MyApp/0.1 ");
my $res = $ua->request($req);
if ( not $res->is_success ) {
print "HTTP get code: ", $res->code, "\n";
print "HTTP get msg : ", $res->message, "\n";
use Data::Dump qw/ dd /;
dd( $res->as_string );
$_ = $res->code . ": " . $res->message;
die "ERROR: $_";
} ## end if ( not $res->is_success)
my $cont = $res->decoded_content; # content, decoded if it was zipped
$cont = decode( 'UTF-8', $cont )
; # for some reason this is required and not included in $res->decoded_content
# logIt("response content:\n$cont");
return $cont;
} ## end sub getContfromURL
sub PostPutJsonToURL {
# Put/Update/Set content to url, using HTTP PUT
# in:
# $postPut [POST, PUT]
# $url
# $token
# $silent [0,1] (1-> do not die on http error)
# $json content, can be ""
# out: string of contents
my ( $postPut, $url, $token, $silent, $json ) = @_; # () important!!!
logSubStart('PostPutJsonToURL');
logIt("$postPut url='$url'");
my $req;
if ( $postPut eq 'POST' ) {
$req = HTTP::Request->new( POST => $url );
}
elsif ( $postPut eq 'PUT' ) {
$req = HTTP::Request->new( PUT => $url );
}
else {
die "Bad parameter '$postPut'";
}
logIt("json-content:\n$json");
$req->content($json);
$req->header( 'Accept' => 'application/json' );
$req->header( 'Accept-Encoding' => 'UTF-8' );
$req->header( 'Authorization' => "Bearer $token" );
$req->header( 'Content-Type' => 'application/json' );
#creat User Agent using LWP
my $ua = LWP::UserAgent->new();
# $ua->agent("MyApp/0.1 ");
# $ua->default_header( 'Content-Type' => "application/json" );
my $res = $ua->request($req);
my $htmlcode = $res->code;
if ( $silent == 0 and not $res->is_success ) {
print "HTTP get code: ", $htmlcode, "\n";
print "HTTP get msg : ", $res->message, "\n";
# use Data::Dump qw/ dd /;
# dd( $res->as_string );
die "leaving";
} ## end if ( $silent == 0 and ...)
my $cont = $res->decoded_content; # content, decoded if it was zipped
$cont = decode( 'UTF-8', $cont );
logIt("response content:\n$cont");
return ( $htmlcode, $cont );
} ## end sub PostPutJsonToURL
sub convertJSONcont2Hash {
# in: json string, containing a single json object
# out: a single hash (multidimensional)
my ($cont) = @_; # () important!!!
logSubStart('convertJSONcont2Hash');
# say "<p><code>debug for Dave 2:<br>json= '$cont'</code></p>";
my $j = JSON->new->allow_nonref;
my $decoded = {}; # empty hash ref
if ( length($cont) > 0 ) {
$decoded = $j->decode($cont);
die "E: message '$decoded' is no HASHREF"
if ( not ref($decoded) eq "HASH" );
}
return %{$decoded}; # ref -> hash
} ## end sub convertJSONcont2Hash
sub convertJSONcont2Array {
# in: json string, containing a list of json objects
# out: an array containing hashes
my ($cont) = @_; # () important!!!
logSubStart('convertJSONcont2Array');
my $decoded = JSON->new->allow_nonref->decode($cont);
# my $j = JSON->new->allow_nonref;
# my $decoded = $j->decode($cont);
die "E: message '$decoded' is no ARRAYREF"
if ( not ref($decoded) eq "ARRAY" );
return @{$decoded}; # ref -> list
} ## end sub convertJSONcont2Array
# sub convertArray2Hash {
# # in: array
# # out: hash, indexed by array index
# # convert array to hash, indexed by number $i
# # not used any more, but might be of use later?
# my @L = @_;
# my %h;
# for my $i ( 0 .. $#L ) {
# $h{$i} = $L[$i];
# }
# return %h;
# }
sub ref2String {
# used for converting hash values, being a hashref oder an arrayref itself to a string
# in: $field = a value of a hash entry
# out: string $field, if $field is a hash or array ref, it is converted to a string, recursively
# else $field is returned untouched
my ($field) = @_;
# logSubStart ('ref2String');
if ( ref($field) eq 'HASH' ) {
my %h = %{$field};
my $s = "";
foreach my $k ( sort keys %h ) {
if ( not defined $h{$k} ) { $h{$k} = ""; }
my $s2 = $h{$k};
if ( ref($s2) eq 'HASH' or ref($s2) eq 'ARRAY' ) {
$s2 = ref2String($s2); # recursion
}
$s .= "$k=$s2, ";
} ## end foreach my $k ( sort keys %h)
$s = substr $s, 0, length( $s - 2 ); # remove last ', '
$field = "{$s}";
} ## end if ( ref($field) eq 'HASH')
elsif ( ref($field) eq 'ARRAY' ) {
my @L = @{$field};
my $s = "";
foreach my $s2 (@L) {
if ( ref($s2) eq 'HASH' or ref($s2) eq 'ARRAY' ) {
$s2 = ref2String($s2); # recursion
}
$s .= "$s2, ";
} ## end foreach my $s2 (@L)
$s = substr $s, 0, length($s) - 2; # remove last ', '
$field = "[$s]";
} ## end elsif ( ref($field) eq 'ARRAY')
return $field;
} ## end sub ref2String
sub convertJsonFilesToArrayOfHashes {
# in: @L list of json filenames
# out: array of hashes of the json contents
# array of hashes, to ensure the order of the elements
# writes the array to a .dmp file for reuse
my @L = @_; # List of JSON files
logSubStart('convertJsonFilesToArrayOfHashes');
my @allActivityHashes;
foreach my $fileIn (@L) {
open my $fhIn, '<:encoding(UTF-8)', $fileIn
or die "ERROR: Can't read from file '$fileIn': $!";
my $cont;
{
$/ = undef; # slurp
$cont = <$fhIn>;
}
close $fhIn;
if ( $cont =~ m/^\[\{/ )
{ # for activityList the decoded JSON is a List -> ARRAYREF
my @activitiesOfThisFile = convertJSONcont2Array($cont);
push @allActivityHashes, @activitiesOfThisFile;
}
elsif ( $cont =~ m/^\{/ )
{ # for single activity the decoded JSON is a Hash -> HASHREF
my %h = convertJSONcont2Hash($cont);
push @allActivityHashes, $_;
}
print ".<br>";
} # foreach my $fileIn (@L)
return @allActivityHashes;
} ## end sub convertJsonFilesToArrayOfHashes
sub extractActivityIdFromJsonFiles {
# read stored JSONs (of the activities) and extract activity IDs
# in: @L # Array of JSON files
# out: @IDs # Array of IDs
# TODO: use ..dmp file instead? or pace this logic into another sub
my @L = @_; # List of JSON files
logSubStart('extractActivityIdFromJsonFiles');
my @IDs;
my @allActivityHashes = convertJsonFilesToArrayOfHashes(@L);
foreach my $activity (@allActivityHashes) {
my %h = %{$activity}; # each $activity is a hashref
# say "$h{'id'}\t$h{'type'}\t$h{'start_date_local'}\t$h{'name'}";
push @IDs, $h{'id'};
}
return @IDs;
} ## end sub extractActivityIdFromJsonFiles
sub getKnownLocationsOfUser {
# $stravaUserID fetched from $s
# out: @knownLocations as array of arrays: [$lat,$lon,$description]
logSubStart('getKnownLocationsOfUser');
# my $stravaUserID = $s{'stravaUserID'};
my @knownLocations = ();
# some global hard coded ones
@knownLocations = (
[ 49.574986, 10.967483, "ER-Schaeffler-SMB" ],
[ 51.070298, 13.760067, "DD-Alaunpark" ],
[ 53.330333, 10.138152, "P-MTV-Pattensen" ],
[ 51.010218, 13.701419, 'DD-Robotron' ],
[ 49.60579, 11.036603, 'ER-Meilwald-Handtuchwiese' ],
[ 49.588036, 11.035357, "ER-ObiKreisel" ]
);
# logIt("knownLocations bevor");
# logIt(Dumper \@knownLocations);
push @knownLocations, readKnownLocationsFromFile();
# logIt("knownLocations danach");
# logIt(Dumper \@knownLocations);
return @knownLocations;
} ## end sub getKnownLocationsOfUser
sub readKnownLocationsFromFile {
# Read known locations from file $stravaUserID.txt
# format of file: "$lat $lon "description (without spaces)\n" , so separated columns by " "
# In: nothing
# out @knownLocations as array of arrays: [$lat,$lon,$description]
my $filename = "$o{'dirKnownLocationsBase'}/$s{'stravaUserID'}.txt";
logSubStart('readKnownLocationsFromFile');
my @knownLocations = ();
if ( -f $filename ) {
# say "$filename found";
open my $fhIn, '<:encoding(UTF-8)', $filename or die;
my @L2;
{
$/ = "\n"; # set end of line for reading of file
@L2 = <$fhIn>;
close $fhIn;
}
chomp @L2; # remove \n from lineend
my $i = 0;
foreach my $line (@L2) {
# logIt ("$i: $line");
my @L3 = split " ", $line;
$knownLocations[$i] = [ $L3[0] + 0, $L3[1] + 0, $L3[2] ];
$i++;
} ## end foreach my $line (@L2)
} ## end if ( -f $filename )
# logIt ("Number of items in knownLocations:" . $#knownLocations) ;
# logIt ("readKnownLocationsFromFile : knownLocations = ");
# logIt (Dumper \@knownLocations);
return @knownLocations;
} ## end sub readKnownLocationsFromFile
sub convertActivityHashToExcel {
# converts hash of activities and exports to an excel file
# creates path to output file if not present
# in: $fileNameExcel
# @L allActivityHashes of activities
# out: excel file: $fileOutExcel = "$s{'tmpDownloadFolder'}/$fileNameExcel";
# Info:
# average_watts = kilojoules * 1000 * moving_time
# average_cadence = halbe Schrittfreq
# new calculated fields are marked with x_
my $fileNameExcel = shift;
my @allActivityHashes = @_; # List of JSON files
logSubStart('convertActivityHashToExcel');
my $fileOutExcel = "$s{'tmpDownloadFolder'}/$fileNameExcel";
$_ = dirname($fileOutExcel);
make_path $_ unless -d $_;
# check for each activity which parameters are present, to ensure that all parameters are included
my %hashOfActivitiyParameters;
foreach my $activity (@allActivityHashes) {
my %h = %{$activity}; # each $activity is a hashref
foreach my $key ( keys %h ) {
$hashOfActivitiyParameters{$key}++;
}
} ## end foreach my $activity (@allActivityHashes)
# # count how often each activity parameter is used
# my %h = %hashOfActivitiyParameters;
# foreach my $k ( sort keys(%h) ) {
# say "$k\t$h{$k}";
# }
# export all activities and all parameters to a new Excel sheet
use Excel::Writer::XLSX;
logIt("creating Excel '$fileOutExcel'");
my $workbook = Excel::Writer::XLSX->new($fileOutExcel)
or die "ERROR: Can't open $fileOutExcel for writing!\n";
$workbook->set_properties(
title => 'Strava Excel Activity Export',
author => 'Torben Menke',
comments =>
'https://entorb.net/strava/ created with Perl and Excel::Writer::XLSX',
category => 'Sport'
);
my $worksheet = $workbook->add_worksheet("ActivityListData");
my $formatHeaderRow = $workbook->add_format( bold => 1 ); # color => 'red'
my $formatDate
= $workbook->add_format( num_format => 'dd.mm.yyyy hh:mm:ss' ) #
; # for *display* in Excel
# Add a handler to store the width of the longest string written to a column.
# We use the stored width to simulate an autofit of the column widths.
#
# You should do this for every worksheet you want to autofit.
$worksheet->add_write_handler( qr[\w], \&excel_store_excel_string_widths );
my @Reihenfolge;
@Reihenfolge = qw(
id
type
x_gear_name
start_date_local
x_week
x_start_h
name
x_min
x_km
x_min/km
km/h
x_max_km/h
x_mi
x_min/mi
x_mph
x_max_mph
total_elevation_gain
x_elev_m/km
average_heartrate
max_heartrate
average_cadence
average_watts
kilojoules
commute
private
visibility
workout_type
x_nearest_city_start
x_start_locality
x_end_locality
x_dist_start_end_km
start_latlng
end_latlng
elev_low
elev_high
kudos_count
comment_count
);
# now add the remaining fields
# get the delta
my %in_R = map { $_ => 1 } @Reihenfolge;
push @Reihenfolge,
grep { not $in_R{$_} } sort keys %hashOfActivitiyParameters;
# print Dumper @Reihenfolge;
my $s = \@Reihenfolge;
my $line = 0; # starts at 0
$worksheet->write( $line, 0, $s, $formatHeaderRow ); # header row
# klappt leider nicht:
# # write format into column C (date)
# for my $i ( 2 .. 10 ) {
# $worksheet->write( $i, 2, "", $formatDate );
# }
foreach my $activity (@allActivityHashes) {
my %h = %{$activity}; # each $activity is a hashref
# say $h{"name"};
# $h{"date"} = convertDate4Excel( $h{"start_date_local"} );
my @L = map { $h{$_} } @Reihenfolge;
# for (my $i=0; $i<=$#Reihenfolge; $i++) {
# say "$Reihenfolge[$i] : $L[$i]";
# }
# die;
foreach my $field (@L) {
# some fields are hashrefs or arrayrefs
# convert them to a string
if ( not defined $field ) {
$field = "";
}
elsif ( ref($field) eq 'HASH' or ref($field) eq 'ARRAY' ) {
$field = ref2String($field);
if ( length($field) > 64 ) {
$field = substr( $field, 0, 64 ) . '...';
}
} ## end elsif ( ref($field) eq 'HASH'...)
} # foreach my $field (@L)
$s = \@L;
$line++;
$worksheet->write( $line, 0, $s ); # data row
# TODO: overwrite data formatted using date format
# Excel requires dates to be formatted in ISO8601 format
# 2018-08-28 or 2018-08-28T14:24:22+00:00 or 2018-08-28T14:24:22Z or 20180828T142422Z
my $index;
($index)
= grep { $Reihenfolge[$_] eq "start_date_local" } 0 .. $#Reihenfolge;
$worksheet->write_date_time( $line, $index, $h{"start_date_local"},
$formatDate );
($index) = grep { $Reihenfolge[$_] eq "start_date" } 0 .. $#Reihenfolge;
$worksheet->write_date_time( $line, $index, $h{"start_date"},
$formatDate );
} ## end foreach my $activity (@allActivityHashes)
# Run the autofit after you have finished writing strings to the workbook.
excel_autofit_columns($worksheet)
; # from # https://metacpan.org/pod/Spreadsheet::WriteExcel::Examples#Example:-autofit.pl
$workbook->close;
return;
} ## end sub convertActivityHashToExcel
sub convertFetchedActivityListJsonFilesToExcel {
# wrapper for backward compatibility
# converts array of filenames to list of hashes
# calls convertActivityHashToExcel
# in: $fileNameExcel
# $refKnownLocations arrayref of known locations
# @L Array of filenames of json files of activities, either one file per activity or files containing lists of activities
# out: excel file: $fileOutExcel = "$s{'tmpDownloadFolder'}/$fileNameExcel";
my $fileNameExcel = shift;
my $refKnownLocations = shift;
my @L = @_; # List of JSON files
logSubStart('convertFetchedActivityListJsonFilesToExcel');
my @allActivityHashes = convertJsonFilesToArrayOfHashes(@L);
convertActivityHashToExcel( $fileNameExcel, $refKnownLocations,
@allActivityHashes );
return;
} ## end sub convertFetchedActivityListJsonFilesToExcel
sub sortArrayHashRefsNumAsc {
my ( $fieldname, @list ) = @_;
my @sorted = sort {
my ( $aRef, $bRef ) = ( $a, $b );
my %aHash = %{$aRef};
my %bHash = %{$bRef};
$aHash{$fieldname} <=> $bHash{$fieldname};
} @list;
return @sorted;
} ## end sub sortArrayHashRefsNumAsc
sub sortArrayHashRefsNumDesc {
my ( $fieldname, @list ) = @_;
my @sorted = sort {
my ( $aRef, $bRef ) = ( $a, $b );
my %aHash = %{$aRef};
my %bHash = %{$bRef};
$bHash{$fieldname} <=> $aHash{$fieldname};
} @list;
return @sorted;
} ## end sub sortArrayHashRefsNumDesc
sub sortArrayHashRefsAbcAsc {
my ( $fieldname, @list ) = @_;
my @sorted = sort {
my ( $aRef, $bRef ) = ( $a, $b );
my %aHash = %{$aRef};
my %bHash = %{$bRef};
$aHash{$fieldname} cmp $bHash{$fieldname};
} @list;
return @sorted;
} ## end sub sortArrayHashRefsAbcAsc
sub zipFiles {
# Zipping of activityJSONs
# in: $pathToZip, @files , both in absolute path
# out: nothing
my ( $pathToZip, @files ) = @_;
logSubStart('zipFiles');
logSubStart( join "\n", @files );
use IO::Compress::Zip qw(zip $ZipError);
zip \@files => $pathToZip,
FilterName => sub {s<.*[/\\]><>} # trim path, filename only
,
TextFlag =>
1 # It is used to signal that the data stored in the zip file/buffer is probably text.
,
CanonicalName =>
1 # This option controls whether the filename field in the zip header is normalized into Unix format before being written to the zip file.
,
ZipComment => "Created by Torben's Strava App https://entorb.net/strava"
# , Level => 9 # [0..9], 0=none, 9=best compression
or die "zip failed: $ZipError\n";
return;
} ## end sub zipFiles
sub fetchSegmentsStarred {
# fetch starred segments from Strava
# in: Token
# out: array of SummarySegment
my ($token) = @_;
logSubStart('fetchSegmentsStarred');
my $cont = getContfromURL(
"$o{'urlStravaAPI'}/segments/starred?per_page=200&page=1", $token );
my @L = convertJSONcont2Array($cont);
return sortArrayHashRefsAbcAsc( 'name', @L );
} ## end sub fetchSegmentsStarred
sub fetchGearName {
# fetch gear details from Strava
# in: Token, gear_id
# out: str: gear name
my ( $token, $gear_id ) = @_;
logSubStart('fetchGear');
my $cont = getContfromURL( "$o{'urlStravaAPI'}/gear/$gear_id", $token );
my %h = convertJSONcont2Hash($cont);
return $h{'name'}; # name, brand_name, model_name, description, distance
} ## end sub fetchGearName
sub fetchSegment {
# fetch segment
# in: Token, segmentid
# out: hash
my ( $token, $segmentid ) = @_;
logSubStart('fetchSegment');
my $cont
= getContfromURL( "$o{'urlStravaAPI'}/segments/$segmentid", $token );
my %h = convertJSONcont2Hash($cont);
return %h;
} ## end sub fetchSegment
sub fetchSegmentRecord {
# fetch leaderboard rank 1
# in: Token, segmentid
# out: count of athlets, time of rank 1
my ( $token, $segmentid ) = @_;
logSubStart('fetchSegmentRecord');
my $cont
= getContfromURL(
"$o{'urlStravaAPI'}/segments/$segmentid/leaderboard?per_page=1&page=1",
$token );
my %h = convertJSONcont2Hash($cont);
my $entry_count = $h{"entry_count"};
my $record_time = $h{"entries"}[0]{"elapsed_time"};
return ( $entry_count, $record_time );
} ## end sub fetchSegmentRecord
sub fetchSegmentLeaderboard {
my ( $token, $segment_id, $date_range, $club_id, $gender, $age_group ) = @_;
logSubStart('fetchSegmentLeaderboard');
# validate date_range
$date_range = ""
unless grep { $date_range eq $_ }
qw (this_year this_month this_week today);
$club_id = "" if $club_id == 0;
my $page = 1;
my $lastpage = 0;
my $entry_count = 0;
my @list;
if ( $gender eq 'men' ) { $gender = 'M'; }
elsif ( $gender eq 'women' ) { $gender = 'F'; }
else { $gender = ''; }
$age_group = '' if ( $age_group eq 'all_age' );
while ( $lastpage != 1 and $page <= 10 ) {
my $url
= "$o{ 'urlStravaAPI' }/segments/$segment_id/leaderboard?per_page=200&following=false&gender=$gender&age_group=$age_group&date_range=$date_range&club_id=$club_id&page=$page";
my $cont = getContfromURL( $url, $token );
my %h = convertJSONcont2Hash($cont);
$entry_count = $h{"entry_count"} if $entry_count == 0;
my @entries_this_page = @{ $h{"entries"} };
$lastpage = 1 if ( $#entries_this_page < 200 );
foreach my $hashref (@entries_this_page) {
my %h2 = %{$hashref};
my $listref = [
$h2{"rank"}, $h2{"elapsed_time"},
$h2{"athlete_name"}, formatDate( $h2{"start_date_local"}, 'date' )
];
push( @list, $listref );
} ## end foreach my $hashref (@entries_this_page)
# {
# 'start_date_local' => '2019-02-28T15:08:36Z',
# 'start_date' => '2019-02-28T14:08:36Z',
# 'rank' => 182,
# 'moving_time' => 133,
# 'elapsed_time' => 133,
# 'athlete_name' => 'xxxx'
# };
$page += 1;
} ## end while ( $lastpage != 1 and...)
# print Dumper @list;
return @list;
} ## end sub fetchSegmentLeaderboard
sub fetchClubs {
# TODO: caching via $s{ 'pathToClubsHashDump' }
my ($token) = @_;
logSubStart('fetchClubs');
my @list;
my $url = "$o{ 'urlStravaAPI' }/athlete/clubs?per_page=200";
my $cont = getContfromURL( $url, $token );
my @l = convertJSONcont2Array($cont);
foreach my $hashref (@l) {
my %h2 = %{$hashref};
my $listref = [
$h2{"id"}, $h2{"name"}, $h2{"member_count"},
$h2{"sport_type"}, $h2{"city"}
];
push( @list, $listref );
} ## end foreach my $hashref (@l)
return @list;
} ## end sub fetchClubs
sub formatDate {
# convert 2019-05-16T14:18:00Z -> 2019-05-16 14:18:00
my ( $date, $format ) = @_;
logSubStart('formatDate');
if ( $format eq 'datetime' ) {
$date =~ s/^(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})Z$/$1 $2/;
}
elsif ( $format eq 'date' ) {
$date =~ s/^(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})Z$/$1/;
}
else {
die "format '$format' unknown";
}
return $date;
} ## end sub formatDate
sub secToMinSec {
# convert 123s -> 02:03
my ($sek) = @_;
logSubStart('secToMinSec');
my $minDec = $sek / 60;
my $m = int($minDec);
my $s = ( $minDec - $m ) * 60;
return sprintf "%02d:%02d", $m, $s;
} ## end sub secToMinSec
sub activityUrl {
# in: activity ID, name
# out: <a href="https://www.strava.com/activities/<id>" target="_blank"><name></a>
my ( $id, $name ) = @_;
return
'<a href="https://www.strava.com/activities/'
. $id
. '" target="_blank">'
. $name . '</a>';
} ## end sub activityUrl
sub htmlPrintHeader {
# print html header using $cgi->header and $cgi->start_html
# in: $title, can be ""
# if $printNavi == 0 -> no navi and title are printed
my ( $cgi, $title ) = @_;
my $titleLong;
logSubStart('htmlPrintHeader');
if ( $title eq '' ) {
$title = "Torben\'s Strava Äpp";
$titleLong = $title;
}
else {
$titleLong = "Torben\'s Strava Äpp - $title";
}
# print html header
print $cgi->header(
-type => 'text/html',
-charset => 'utf-8'
);
my $html = $cgi->start_html(
-title => $titleLong,
-meta => { 'author' => 'Torben Menke' }
# ,-author=>'Torben Menke' # generates mailto:
,
-style => { -src => [ '/style.css', './style-strava.css' ] }
# -style => { -src => './style-strava.css' }
);
# CGI.pm doesn't support HTML5 DTD; replace the one it puts in.
$html =~ s{<!DOCTYPE.*?>}{<!DOCTYPE html>}s;
$html =~ s{ */>}{>}sg;
say $html;
say "<h1_title><h1>$title</h1></h1_title>";
return;
} ## end sub htmlPrintHeader
sub htmlPrintFooter {
# print html footer using $cgi->end_html and close main div
# in: $cgi
my ($cgi) = @_;
logSubStart('htmlPrintFooter');
say '</div>';
say $cgi->end_html;
} ## end sub htmlPrintFooter
sub htmlPrintNavigation {
# prints the menu of available features
# reads $session from %s
logSubStart('htmlPrintNavigation');
say '<div id="mySidenav" class="sidenav">';
# my $buttonlayout = 'style="height:44px; width:200px"';
my $missingActivityCacheDisablesButton
= -f $s{'pathToActivityListHashDump'} ? '' : ' disabled="disabled"';
my $missingScopeActivityWriteDisablesButton
= $s{'scope'} =~ m/activity:write/ ? '' : ' disabled="disabled"';
my $countActCached = 0;
if ( -f $s{'pathToActivityListHashDump'} ) {
my @allActivityHashes = @{ retrieve( $s{'pathToActivityListHashDump'} ) }