blib/lib/Net/Google/Spreadsheets/V4.pm

filter: Statementstmt 37.3% 43 / 115 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 58.3% 14 / 24 Podpod 57.1% 4 / 7 totaltotal 30.6% 61 / 199 CC 25 SCAR 40.5
CC
25
Cov
27%
request
182.0
get_sheet
42.0
__ANON__
20.0
CRAP 57.6
↑ Summary Build »
1 package Net::Google::Spreadsheets::V4;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use 5.010_000;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 our $VERSION = '0.002';
9  
10 use Class::Accessor::Lite (
11 2 new => 0,
12 ro => [qw(ua csv spreadsheet_id endpoint)],
13 2 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 2 ▶use Data::Validator;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use Log::Minimal env_debug => 'NGS4_DEBUG';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use Net::Google::DataAPI::Auth::OAuth2;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use Net::OAuth2::AccessToken;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶use Text::CSV;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶use Furl;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 2 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 2 ▶use Sub::Retry;
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 sub new {
26 0 ▶ state $rule = Data::Validator->new(
Subroutine new: not called CC=1 SCAR=6.9
Pod documented
27 client_id => { isa => 'Str' },
28 client_secret => { isa => 'Str' },
29 refresh_token => { isa => 'Str' },
30  
31 spreadsheet_id => { isa => 'Str' },
32 timeout => { isa => 'Int', default => 120 },
33 )->with('Method','AllowExtra');
34 0 my($class, $args) = $rule->validate(@_);
35  
36 my $self = bless {
37 %$args,
38 ua => undef,
39 csv => Text::CSV->new({ binary => 1}),
40 endpoint => 'https://sheets.googleapis.com/v4/spreadsheets/'.$args->{spreadsheet_id},
41 0 }, $class;
42  
43 0 $self->_initialize;
44  
45 0 return $self;
46 }
47  
48 sub _initialize {
49 0 ▶ my($self) = @_;
Subroutine _initialize: not called CC=2 SCAR=17.9
50  
51 0 my $account = {
52 auth_provider_x509_cert_url => 'https://www.googleapis.com/oauth2/v1/certs',
53 auth_uri => 'https://accounts.google.com/o/oauth2/auth',
54 redirect_uris => [
55 'urn:ietf:wg:oauth:2.0:oob',
56 'http://localhost'
57 ],
58 token_uri => 'https://accounts.google.com/o/oauth2/token',
59 };
60  
61 0 for my $f (qw(client_id client_secret refresh_token)) {
62 0 $account->{$f} = $self->{$f};
63 }
64  
65 my $oauth2 = Net::Google::DataAPI::Auth::OAuth2->new(
66 client_id => $account->{client_id},
67 client_secret => $account->{client_secret},
68 0 scope => [qw(
69 https://www.googleapis.com/auth/drive
70 https://www.googleapis.com/auth/drive.readonly
71 https://www.googleapis.com/auth/spreadsheets
72 https://www.googleapis.com/auth/spreadsheets.readonly
73 )],
74 );
75  
76 0 my $ow = $oauth2->oauth2_webserver;
77 my $token = Net::OAuth2::AccessToken->new(
78 profile => $ow,
79 auto_refresh => 1,
80 refresh_token => $account->{refresh_token},
81 0 );
82 0 $ow->update_access_token($token);
83 0 $token->refresh;
84 0 $oauth2->access_token($token);
85  
86 $self->{ua} = Furl->new(
87 headers => [ 'Authorization' => sprintf('Bearer %s', $token->access_token) ],
88 timeout => $self->{timeout},
89 0 );
90 }
91  
92 sub request {
93 0 ▶ my($self, $method, $url, $content, $opt) = @_;
Subroutine request: not called CC=13 SCAR=52.0
Pod undocumented
94  
95 $opt = {
96 retry_times => 3,
97 retry_interval => 1.0,
98 0 ▶ %{ $opt // {} },
Condition0%0/2
$opt // {}
l!l
00
MC/DC0%0/1
$opt // {}
$opt
Truth table0%0/2
A
A= $opt
Aresult
11
00
99 };
100  
101 0 $url = $self->endpoint . $url;
102  
103 0 ▶ debugf("request: %s => %s %s %s", $method, $url, ddf($content//'{no content}'), ddf($opt//'no opt'));
Condition0%0/4
$content // "{no content}"
l!l
00
$opt // "no opt"
l!l
00
MC/DC0%0/1
$content // "{no content}"
$content
MC/DC0%0/1
$opt // "no opt"
$opt
Truth table0%0/2
A
A= $content
Aresult
11
00
Truth table0%0/2
A
A= $opt
Aresult
11
00
104  
105 0 my $headers = [];
106 0 ▶ if ($content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content) 0 0 0
107 0 push @$headers, 'Content-Type' => 'application/json';
108 }
109 0 ▶ if ($opt->{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"headers"}) 0 0 0
110 0 push @$headers, @{ $opt->{headers} };
111 }
112  
113 my $res = retry $opt->{retry_times}, $opt->{retry_interval}, sub {
114 0 ▶ $self->ua->request(
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$content ? : 0 0 0
115 method => $method,
116 url => $url,
117 headers => $headers,
118 $content ? (content => encode_json($content)) : (),
119 );
120 }, sub {
121 0 ▶ my $res = shift;
Subroutine __ANON__: not called CC=4 SCAR=30.0
122 0 ▶ if (!$res) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $res) { } 0 0 0
elsif ($res->status_line =~ /^500\s+Internal Response/ or $res->code =~ /^50[234]$/) { } 0 0 0
123 0 warnf "not HTTP::Response: $@";
124 0 return 1;
125 ▶ } elsif ($res->status_line =~ /^500\s+Internal Response/
Condition0%0/3
$res->status_line =~ /^500\s+Internal Response/ or $res->code =~ /^50[234]$/
l!l&&r!l&&!r
000
MC/DC0%0/2
$res->status_line =~ /^500\s+Internal Response/ or $res->code =~ /^50[234]$/
$res->status_line =~ /^500\s+Internal Response/ $res->code =~ /^50[234]$/
Truth table0%0/3
A or B
A= $res->status_line =~ /^500\s+Internal Response/B= $res->code =~ /^50[234]$/
ABresult
1X1
011
000
126 or $res->code =~ /^50[234]$/
127 ) {
128 0 warnf 'retrying: %s', $res->status_line;
129 0 return 1; # do retry
130 } else {
131 0 return;
132 }
133 0 };
134  
135 0 ▶ if (!$res) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $res) { } 0 0 0
136 0 ▶ critf 'failure %s %s %s', $method, $url, ddf($content//'{no content}');
Condition0%0/2
$content // "{no content}"
l!l
00
MC/DC0%0/1
$content // "{no content}"
$content
Truth table0%0/2
A
A= $content
Aresult
11
00
137 0 return;
138 } else {
139 0 ▶ if ($res->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_success) { } 0 0 0
140 0 ▶ my $res_content = $res->decoded_content ? decode_json($res->decoded_content) : 1;
Branch: 1 branch
BranchTrueFalseTotal
$res->decoded_content ? : 0 0 0
141 0 ▶ return wantarray ? ($res_content, $res) : $res_content;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
142 } else {
143 0 ▶ critf 'failure %s %s %s: %s', $method, $url, ddf($content//'{no content}'), $res->status_line;
Condition0%0/2
$content // "{no content}"
l!l
00
MC/DC0%0/1
$content // "{no content}"
$content
Truth table0%0/2
A
A= $content
Aresult
11
00
144 0 ▶ return wantarray ? ('', $res) : '';
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
145 }
146 }
147 }
148  
149 sub get_sheet {
150 0 ▶ state $rule = Data::Validator->new(
Subroutine get_sheet: not called CC=6 SCAR=37.4
Pod documented
151 title => { isa => 'Str', xor => [qw(index sheet_id)] },
152 index => { isa => 'Str', xor => [qw(title sheet_id)] },
153 sheet_id => { isa => 'Str', xor => [qw(title index )] },
154 )->with('Method');
155 0 my($self, $args) = $rule->validate(@_);
156  
157 0 my($pkey, $akey);
158 0 for my $key (qw(title index sheet_id)) {
159 0 ▶ next unless exists $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{$key} 0 0 0
160 0 $akey = $key;
161 $pkey = {
162 sheet_id => 'sheetId',
163 0 ▶ }->{$key} // $key;
Condition0%0/3
{"sheet_id", "sheetId"}->{$key} // $key
l!l&&r!l&&!r
000
MC/DC0%0/2
{"sheet_id", "sheetId"}->{$key} // $key
{"sheet_id", "sheetId"}->{$key} $key
Truth table0%0/3
A // B
A= {"sheet_id", "sheetId"}->{$key}B= $key
ABresult
1X1
011
000
164 }
165  
166 0 my($content) = $self->request(GET => '');
167 0 for my $sheet (@{ $content->{sheets} }) {
168 0 ▶ if ($sheet->{properties}{$pkey} eq $args->{$akey}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sheet->{"properties"}{$pkey} eq $args->{$akey}) 0 0 0
169 0 return $sheet;
170 }
171 }
172  
173 0 return;
174 }
175  
176 sub clear_sheet {
177 0 ▶ state $rule = Data::Validator->new(
Subroutine clear_sheet: not called CC=1 SCAR=6.9
Pod documented
178 sheet_id => { isa => 'Str' },
179 )->with('Method');
180 0 my($self, $args) = $rule->validate(@_);
181  
182 return $self->request(
183 POST => ':batchUpdate',
184 {
185 requests => [
186 {
187 repeatCell => {
188 range => {
189 sheetId => $args->{sheet_id},
190 },
191 0 cell => {
192 },
193 fields => '*',
194 },
195 },
196 ],
197 },
198 );
199 }
200  
201 # https://developers.google.com/sheets/guides/concepts#a1_notation
202 sub a1_notaion {
203 0 ▶ state $rule = Data::Validator->new(
Subroutine a1_notaion: not called CC=1 SCAR=6.9
Pod undocumented
204 sheet_title => { isa => 'Str' },
205 start_column => { isa => 'Int', default => 1 },
206 end_column => { isa => 'Int' },
207 start_row => { isa => 'Int', default => 1 },
208 end_row => { isa => 'Int' },
209 )->with('Method');
210 0 my($self, $args) = $rule->validate(@_);
211  
212 return sprintf('%s!%s%d:%s%d',
213 $args->{sheet_title},
214 $self->column_notation($args->{start_column}),
215 $args->{start_row},
216 $self->column_notation($args->{end_column}),
217 $args->{end_row},
218 0 );
219 }
220  
221 sub column_notation {
222 0 ▶ my($self, $n) = @_;
Subroutine column_notation: not called CC=2 SCAR=17.9
Pod undocumented
223  
224 0 my $l = int($n / 27);
225 0 my $r = $n - $l * 26;
226  
227 0 ▶ if ($l > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l > 0) { } 0 0 0
228 0 return pack 'CC', $l+64, $r+64;
229 } else {
230 0 return pack 'C', $r+64;
231 }
232 }
233  
234 sub to_csv {
235 0 ▶ my $self = shift;
Subroutine to_csv: not called CC=2 SCAR=17.9
Pod documented
236  
237 0 my $status = $self->csv->combine(@_);
238 0 ▶ return $status ? $self->csv->string() : ();
Branch: 1 branch
BranchTrueFalseTotal
$status ? : 0 0 0
239 }
240  
241 2 1;
242  
243 __END__
244  
245 =encoding utf8
246  
247 =begin html
248  
249 <a href="https://travis-ci.org/hirose31/Net-Google-Spreadsheets-V4"><img src="https://travis-ci.org/hirose31/Net-Google-Spreadsheets-V4.png?branch=master" alt="Build Status" /></a>
250 <a href="https://coveralls.io/r/hirose31/Net-Google-Spreadsheets-V4?branch=master"><img src="https://coveralls.io/repos/hirose31/Net-Google-Spreadsheets-V4/badge.png?branch=master" alt="Coverage Status" /></a>
251  
252 =end html
253  
254 =head1 NAME
255  
256 Net::Google::Spreadsheets::V4 - Google Sheets API v4 client
257  
258 =begin readme
259  
260 =head1 INSTALLATION
261  
262 To install this module, run the following commands:
263  
264 perl Build.PL
265 ./Build
266 ./Build test
267 ./Build install
268  
269 =end readme
270  
271 =head1 SYNOPSIS
272  
273 use Net::Google::Spreadsheets::V4;
274
275 my $gs = Net::Google::Spreadsheets::V4->new(
276 client_id => "YOUR_CLIENT_ID",
277 client_secret => "YOUR_CLIENT_SECRET",
278 refresh_token => "YOUR_REFRESH_TOKEN",
279
280 spreadsheet_id => "YOUR_SPREADSHEET_ID",
281 );
282
283 my ($content, $res) = $gs->request(
284 POST => ':batchUpdate',
285 {
286 requests => [ ... ],
287 },
288 );
289  
290 See also examples/import.pl for more complex code.
291  
292 =head1 DESCRIPTION
293  
294 Net::Google::Spreadsheets::V4 is Google Sheets API v4 client
295  
296 =head1 METHODS
297  
298 =head2 Class Methods
299  
300 =head3 B<new>(%args:Hash) :Net::Google::Spreadsheets::V4
301  
302 Creates and returns a new Net::Google::Spreadsheets::V4 client instance. Dies on errors.
303  
304 %args is following:
305  
306 =over 4
307  
308 =item client_id => Str
309  
310 =item client_secret => Str
311  
312 =item refresh_token => Str
313  
314 =item spreadsheet_id => Str
315  
316 =back
317  
318 =head2 Instance Methods
319  
320 =head3 B<get_sheet>(title|index|sheet_id => Str) :HashRef
321  
322 Get C<Sheet> object by title or index or sheet_id.
323  
324 =head3 B<clear_sheet>(sheet_id => Str)
325  
326 Delete all data.
327  
328 =head3 B<to_csv>(Array)
329  
330 Convert Array to CSV Str.
331  
332 =head1 AUTHOR
333  
334 HIROSE Masaaki E<lt>hirose31@gmail.comE<gt>
335  
336 =head1 REPOSITORY
337  
338 L<https://github.com/hirose31/Net-Google-Spreadsheets-V4>
339  
340 git clone https://github.com/hirose31/Net-Google-Spreadsheets-V4.git
341  
342 patches and collaborators are welcome.
343  
344 =head1 SEE ALSO
345  
346 L<https://developers.google.com/sheets/>
347  
348 =head1 COPYRIGHT
349  
350 Copyright HIROSE Masaaki
351  
352 =head1 LICENSE
353  
354 This library is free software; you can redistribute it and/or modify
355 it under the same terms as Perl itself.
356  
357 =cut
358  
359 # for Emacsen
360 # Local Variables:
361 # mode: cperl
362 # cperl-indent-level: 4
363 # cperl-close-paren-offset: -4
364 # cperl-indent-parens-as-block: t
365 # indent-tabs-mode: nil
366 # coding: utf-8
367 # End:
368  
369 # vi: set ts=4 sw=4 sts=0 et ft=perl fenc=utf-8 ff=unix :
↑ Summary Build »