File Coverage

blib/lib/WWW/Connpass/Agent.pm
Criterion Covered Total %
statement 18 45 40.0
branch 0 8 0.0
condition 0 5 0.0
subroutine 6 12 50.0
pod 2 4 50.0
total 26 74 35.1


line stmt bran cond sub pod time code
1             package WWW::Connpass::Agent;
2 1     1   3 use strict;
  1         1  
  1         23  
3 1     1   3 use warnings;
  1         1  
  1         20  
4              
5 1     1   2 use parent qw/WWW::Mechanize/;
  1         2  
  1         5  
6              
7 1     1   67942 use Time::HiRes qw/gettimeofday tv_interval/;
  1         941  
  1         4  
8 1     1   129 use HTTP::Request;
  1         1  
  1         18  
9 1     1   3 use JSON 2;
  1         9  
  1         6  
10              
11             my $_JSON = JSON->new->utf8;
12              
13             sub new {
14 0     0 1   my ($class, %args) = @_;
15 0   0       my $interval = delete $args{interval} || 1.0;
16 0           my $self = $class->SUPER::new(%args);
17 0           $self->{_interval} = $interval;
18 0           $self->{_last_req_at} = undef;
19 0           return $self;
20             }
21              
22             sub request {
23 0     0 1   my $self = shift;
24 0 0         if (my $last_req_at = $self->{_last_req_at}) {
25 0           my $sec = tv_interval($last_req_at);
26 0 0         Time::HiRes::sleep $self->{_interval} - $sec if $sec < $self->{_interval};
27             }
28 0           my $res = $self->SUPER::request(@_);
29 0           $self->{_last_req_at} = [gettimeofday];
30 0           return $res;
31             }
32              
33             sub extract_cookie {
34 0     0 0   my ($self, $expected_key) = @_;
35              
36 0           my $result;
37             $self->cookie_jar->scan(sub {
38 0     0     my ($key, $val) = @_[1..2];
39 0 0         return if defined $result;
40 0 0         return if $key ne $expected_key;
41 0           $result = $val;
42 0           });
43              
44 0           return $result;
45             }
46              
47             sub _csrf_token {
48 0     0     my $self = shift;
49 0   0       $self->{_csrf_token} ||= $self->extract_cookie('connpass-csrftoken');
50             }
51              
52             sub request_like_xhr {
53 0     0 0   my ($self, $method, $url, $param) = @_;
54 0           my $content = $_JSON->encode($param);
55              
56 0           my $req = HTTP::Request->new($method, $url, [
57             'Content-Type' => 'application/json',
58             'Content-Length' => length $content,
59             'X-CSRFToken' => $self->_csrf_token(),
60             'X-Requested-With' => 'XMLHttpRequest',
61             ], $content);
62 0           return $self->request($req);
63             }
64              
65             1;
66             __END__