public
Created

command line tool for training peaks website

  • Download Gist
training_peaks.pl
Perl
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
#!/usr/bin/env perl
 
package WebService::TrainingPeaks;
use Mojo::Base -base;
 
# http://www.trainingpeaks.com/tpwebservices/service.asmx?op=ImportFileForUser
 
use Mojo::UserAgent;
use Mojo::URL;
use Mojo::Asset::File;
use Time::Piece;
 
has [qw/username password/];
has ua => sub { Mojo::UserAgent->new };
has url => sub { Mojo::URL->new('http://www.trainingpeaks.com/tpwebservices/service.asmx/') };
 
sub get_workouts {
my ($self, $start, $end) = @_;
my $url = $self->url->clone->path('GetWorkoutsForAthlete');
 
$end //= localtime;
$start //= $end->add_years(-1);
 
$start = eval { $start->isa('Time::Piece') } ? $start->datetime : "$start";
$end = eval { $end->isa('Time::Piece') } ? $end->datetime : "$end";
 
my $tx = $self->ua->post(
$url,
form => {
username => $self->username,
password => $self->password,
startDate => $start,
endDate => $end,
},
);
 
return $tx->res->dom if $tx->success;
 
die 'Error: ' . $tx->res->body . "\n";
}
 
sub upload_file {
my ($self, $filename) = @_;
my $file = Mojo::Asset::File->new(path => $filename);
 
my $url = $self->url->clone->path('ImportFileForUser');
 
my $tx = $self->ua->post(
$url,
form => {
username => $self->username,
password => $self->password,
byteData => [ unpack 'C*', $file->slurp ],
},
);
 
return 1 if $tx->success;
 
die "Error uploading $filename: " . $tx->res->body . "\n";
}
 
package main;
 
use Mojo::Base -strict;
 
# need credentials here
my $client = WebService::TrainingPeaks->new(
username => ... ,
password => ... ,
);
 
#unless (@ARGV) {
# say for grep {$_} $client->get_workouts->find('HeartRateAverage')->pluck('text')->each;
#}
 
my $command_name = shift or usage();
my $command = __PACKAGE__->can($command_name)
or die "Unknown command $command_name\n";
 
$command->(@ARGV);
 
sub upload {
for my $filename (@_) {
say "$filename uploaded successfully!"
if $client->upload_file($filename);
}
}
 
sub usage {
print "$0 <command> [arguments]\n";
exit;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.