Mojo-GoogleAnalytics

 view release on metacpan or  search on metacpan

lib/Mojo/GoogleAnalytics.pm  view on Meta::CPAN

  '=~'     => [qw(dimension REGEXP)],
  'substr' => [qw(dimension PARTIAL)],
  '=='     => [qw(metric EQUAL)],
  '>'      => [qw(metric GREATER_THAN)],
  '<'      => [qw(metric LESS_THAN)],
);

has authorization => sub { +{} };
has client_email  => sub { Carp::confess('client_email is required') };
has client_id     => sub { Carp::confess('client_id is required') };
has private_key   => sub { Carp::confess('private_key is required') };
has ua            => sub { Mojo::UserAgent->new(max_redirects => 3) };
has view_id => '';

sub authorize {
  my ($self, $cb) = @_;
  my @ua_args = $self->_authorize_ua_args or return $self;

  if ($cb) {
    $self->ua->post(@ua_args, sub { $self->$cb($self->_process_authorize_response($_[1])) });
  }

lib/Mojo/GoogleAnalytics.pm  view on Meta::CPAN

sub _authorize_ua_args {
  my $self = shift;
  my $time = time;
  my $prev = $self->authorization;
  my ($jwt, @ua_args);

  warn "[GoogleAnalytics] Authorization exp: @{[$prev->{exp} ? $prev->{exp} : -1]} < $time\n" if DEBUG;
  return if $prev->{exp} and $time < $prev->{exp};

  $ua_args[0] = Mojo::URL->new($self->{token_uri});
  $jwt = Mojo::JWT->new->algorithm('RS256')->secret($self->private_key);

  $jwt->claims({
    aud   => $ua_args[0]->to_string,
    exp   => $time + 3600,
    iat   => $time,
    iss   => $self->client_email,
    scope => $self->{auth_scope},
  });

  push @ua_args, (form => {grant_type => 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion => $jwt->encode});

lib/Mojo/GoogleAnalytics.pm  view on Meta::CPAN

  $str = $self->client_email;

Example: "some-app@some-project.iam.gserviceaccount.com".

=head2 client_id

  $str = $self->client_id;

Example: "103742165385019792511".

=head2 private_key

  $str = $self->private_key;

Holds the content of a pem file that looks like this:

  -----BEGIN PRIVATE KEY-----
  ...
  ...
  -----END PRIVATE KEY-----

=head2 ua

lib/Mojo/GoogleAnalytics.pm  view on Meta::CPAN

=head2 from_file

  $self = $self->from_file("/path/to/credentials.json");

Used to load attributes from a JSON credentials file, generated from
L<https://console.developers.google.com/apis/credentials>. Example file:

  {
    "type": "service_account",
    "project_id": "cool-project-238176",
    "private_key_id": "01234abc6780dc2a3284851423099daaad8cff92",
    "private_key": "-----BEGIN PRIVATE KEY-----...\n-----END PRIVATE KEY-----\n",
    "client_email": "some-name@cool-project-238176.iam.gserviceaccount.com",
    "client_id": "103742165385019792511",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
  }

Note: The JSON credentials file will probably contain more fields than is
listed above.

=head2 get_report

t/auth.t  view on Meta::CPAN

use Mojo::Base -strict;
use Mojo::GoogleAnalytics;
use Test::More;

plan skip_all => 'TEST_GA_FILE is not set' unless $ENV{TEST_GA_FILE};

my $ga = Mojo::GoogleAnalytics->new($ENV{TEST_GA_FILE});
my $res;

for my $attr (qw(client_email client_id private_key)) {
  ok $ga->$attr, "$attr is set";
}

is $ga->authorize, $ga, 'authorize blocking';
is $ga->authorize, $ga, 'authorize blocking again';
test_authorization('blocking');

is $ga->authorize(sub { Mojo::IOLoop->stop }), $ga, 'authorize non-blocking again';
Mojo::IOLoop->start;

t/mock.t  view on Meta::CPAN

use Mojo::Base -strict;
use Mojo::File 'path';
use Test::More;

BEGIN { $ENV{TEST_MOJO_GA_BATCH_GET_DIR} = path(path(__FILE__)->dirname, 'ga-batch-files')->to_abs }
use Mojo::GoogleAnalytics;

my $ga = Mojo::GoogleAnalytics->new(
  client_email => 'test@example.com',
  client_id    => '100000000000000000000',
  private_key  => sample_private_key(),
);

my $query = {
  viewId     => 'ga:123456789',
  dateRanges => [{startDate => '7daysAgo', endDate => '1daysAgo'}],
  dimensions => [{name => 'ga:country'}, {name => 'ga:browser'}],
  metrics    => [{expression => 'ga:pageviews'}, {expression => 'ga:sessions'}],
  orderBys   => [{fieldName => 'ga:pageviews', sortOrder => 'DESCENDING'}],
  pageSize   => 2,
};

t/mock.t  view on Meta::CPAN

ok !$report->error, 'batch_get_p: error' or diag explain $report->error;

my $err = 'not called';
$ga->{token_uri} = '/no/such/route';
$ga->authorization({});
$ga->authorize_p->catch(sub { $err = shift })->wait;
like $err, qr{Not Found}, 'authorize_p: failed';

done_testing;

sub sample_private_key {
  return <<'HERE';
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEA4qiw8PWs7PpnnC2BUEoDRcwXF8pq8XT1/3Hc3cuUJwX/otNe
fr/Bomr3dtM0ERLN3DrepCXvuzEU5FcJVDUB3sI+pFtjjLBXD/zJmuL3Afg91J9p
79+Dm+43cR6wuKywVJx5DJIdswF6oQDDzhwu89d2V5x02aXB9LqdXkPwiO0eR5s/
xHXgASl+hqDdVL9hLod3iGa9nV7cElCbcl8UVXNPJnQAfaiKazF+hCdl/syrIh0K
CZ5opggsTJibo8qFXBmG4PkT5YbhHE11wYKILwZFSvZ9iddRPQK3CtgFiBnXbVwU
5t67tn9pMizHgypgsfBoeoyBrpTuc4egSCpjsQIDAQABAoIBAF2sU/wxvHbwAhQE
pnXVMMcO0thtOodxzBz3JM2xThhWnVDgxCPkAhWq2X0NSm5n9BY5ajwyxYH6heTc
p6lagtxaMONiNaE2W7TqxzMw696vhnYyL+kH2e9+owEoKucXz4QYatqsJIQPb2vM



( run in 0.229 second using v1.01-cache-2.11-cpan-4d50c553e7e )