blib/lib/Net/Google/Drive/Simple.pm

filter: Statementstmt 19.9% 50 / 251 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 48.4% 16 / 33 Podpod 43.7% 7 / 16 totaltotal 18.9% 73 / 386 CC 42 SCAR 32.7
CC
42
Cov
15%
files
72.0
children_by_folder_id
56.0
children
56.0
CRAP 26.3
↑ Summary
1 ###########################################
2 package Net::Google::Drive::Simple;
3 ###########################################
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use HTTP::Headers;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Sysadm::Install qw( slurp );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use YAML qw( LoadFile DumpFile );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use JSON qw( from_json to_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Test::MockObject;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Log::Log4perl qw(:easy);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use File::MMagic;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use OAuth::Cmdline::GoogleDrive;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 1 our $VERSION = "0.09";
22  
23 ###########################################
24 sub new {
25 ###########################################
26 1 ▶ my($class, %options) = @_;
Subroutine new: called CC=1 SCAR=0.0
Pod documented
27  
28 1 my $self = {
29 init_done => undef,
30 api_file_url => "https://www.googleapis.com/drive/v2/files",
31 api_upload_url => "https://www.googleapis.com/upload/drive/v2/files",
32 oauth => OAuth::Cmdline::GoogleDrive->new( ),
33 %options,
34 };
35  
36 1 bless $self, $class;
37 }
38  
39 ###########################################
40 sub init {
41 ###########################################
42 0 ▶ my( $self, $path ) = @_;
Subroutine init: not called CC=3 SCAR=24.8
Pod undocumented
43  
44 0 ▶ if( $self->{ init_done } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"init_done"}) 0 0 0
45 0 return 1;
46 }
47  
48 0 DEBUG "Testing API";
49 0 ▶ if( !$self->api_test() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->api_test) 0 0 0
50 0 LOGDIE "api_test failed";
51 }
52  
53 0 $self->{ init_done } = 1;
54  
55 0 return 1;
56 }
57  
58 ###########################################
59 sub api_test {
60 ###########################################
61 0 ▶ my( $self ) = @_;
Subroutine api_test: not called CC=2 SCAR=17.9
Pod undocumented
62  
63 0 my $url = $self->file_url( { maxResults => 1 } );
64  
65 0 my $ua = LWP::UserAgent->new();
66  
67 0 my $req = HTTP::Request->new(
68 GET => $url->as_string,
69 );
70 0 $req->header( $self->{ oauth }->authorization_headers() );
71 0 DEBUG "Fetching $url";
72  
73 0 my $resp = $ua->request( $req );
74  
75 0 ▶ if( $resp->is_success() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_success) 0 0 0
76 0 DEBUG "API tested OK";
77 0 return 1;
78 }
79  
80 0 ERROR "API error: ", $resp->message();
81 0 return 0;
82 }
83  
84 ###########################################
85 sub file_url {
86 ###########################################
87 0 ▶ my( $self, $opts ) = @_;
Subroutine file_url: not called CC=2 SCAR=17.9
Pod undocumented
88  
89 0 ▶ $opts = {} if !defined $opts;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $opts 0 0 0
90  
91 0 my $default_opts = {
92 maxResults => 3000,
93 };
94  
95 0 $opts = {
96 %$default_opts,
97 %$opts,
98 };
99  
100 0 my $url = URI->new( $self->{ api_file_url } );
101 0 $url->query_form( $opts );
102  
103 0 return $url;
104 }
105  
106 ###########################################
107 sub files {
108 ###########################################
109 0 ▶ my( $self, $opts, $search_opts ) = @_;
Subroutine files: not called CC=8 SCAR=42.8
Pod documented
110  
111 0 ▶ if( !defined $search_opts ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $search_opts) 0 0 0
112 0 $search_opts = {};
113 }
114 $search_opts = {
115 0 page => 1,
116 %$search_opts,
117 };
118  
119 0 ▶ if( !defined $opts ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts) 0 0 0
120 0 $opts = {};
121 }
122  
123 0 $self->init();
124  
125 0 my @docs = ();
126  
127 0 while( 1 ) {
128 0 my $url = $self->file_url( $opts );
129 0 my $data = $self->http_json( $url );
130 0 my $next_item = $self->item_iterator( $data );
131  
132 0 ▶ while( my $item = $next_item->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = &$next_item()) 0 0 0
133 0 ▶ if( $item->{ kind } eq "drive#file" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item->{'kind'} eq 'drive#file') { } 0 0 0
134 0 my $file = $item->{ originalFilename };
135 0 ▶ if( !defined $file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $file) 0 0 0
136 0 DEBUG "Skipping $item->{ title } (no originalFilename)";
137 0 next;
138 }
139  
140 0 push @docs, $self->data_factory( $item );
141 } else {
142 0 DEBUG "Skipping $item->{ title } ($item->{ kind })";
143 }
144 }
145  
146 0 ▶ if( $search_opts->{ page } and $data->{ nextPageToken } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search_opts->{'page'} and $data->{'nextPageToken'}) { } 0 0 0
Condition0%0/3
$search_opts->{"page"} and $data->{"nextPageToken"}
!ll&&!rl&&r
000
MC/DC0%0/2
$search_opts->{"page"} and $data->{"nextPageToken"}
$search_opts->{"page"} $data->{"nextPageToken"}
Truth table0%0/3
A and B
A= $search_opts->{"page"}B= $data->{"nextPageToken"}
ABresult
0X0
100
111
147 0 $opts->{ pageToken } = $data->{ nextPageToken };
148 } else {
149 0 last;
150 }
151 }
152  
153 0 return \@docs;
154 }
155  
156 ###########################################
157 sub folder_create {
158 ###########################################
159 0 ▶ my( $self, $title, $parent ) = @_;
Subroutine folder_create: not called CC=1 SCAR=6.9
Pod documented
160  
161 0 my $url = URI->new( $self->{ api_file_url } );
162  
163 0 my $data = $self->http_json( $url, {
164 title => $title,
165 parents => [ { id => $parent } ],
166 mimeType => "application/vnd.google-apps.folder",
167 } );
168  
169 0 return $data->{ id };
170 }
171  
172 ###########################################
173 sub file_upload {
174 ###########################################
175 0 ▶ my( $self, $file, $parent_id, $file_id ) = @_;
Subroutine file_upload: not called CC=2 SCAR=17.9
Pod documented
176  
177 # Since a file upload can take a long time, refresh the token
178 # just in case.
179 0 $self->token_expire();
180 0 $self->init();
181  
182 0 my $title = basename $file;
183  
184 # First, insert the file placeholder, according to
185 # http://stackoverflow.com/questions/10317638
186 0 my $file_data = slurp $file;
187 0 my $mime_type = $self->file_mime_type( $file );
188  
189 0 my $url;
190  
191 0 ▶ if( ! defined $file_id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $file_id) 0 0 0
192 0 $url = URI->new( $self->{ api_file_url } );
193  
194 0 my $data = $self->http_json( $url,
195 { mimeType => $mime_type,
196 parents => [ { id => $parent_id } ],
197 title => $title,
198 }
199 );
200  
201 0 $file_id = $data->{ id };
202 }
203  
204 0 $url = URI->new( $self->{ api_upload_url } . "/$file_id" );
205 0 $url->query_form( uploadType => "media" );
206  
207 my $req = &HTTP::Request::Common::PUT(
208 $url->as_string,
209 0 $self->{ oauth }->authorization_headers(),
210 "Content-Type" => $mime_type,
211 Content => $file_data,
212 );
213  
214 0 my $resp = $self->http_loop( $req );
215  
216 0 DEBUG $resp->as_string;
217  
218 0 return $file_id;
219 }
220  
221 ###########################################
222 sub children_by_folder_id {
223 ###########################################
224 0 ▶ my( $self, $folder_id, $opts, $search_opts ) = @_;
Subroutine children_by_folder_id: not called CC=7 SCAR=40.3
Pod undocumented
225  
226 0 $self->init();
227  
228 0 ▶ if( !defined $search_opts ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $search_opts) 0 0 0
229 0 $search_opts = {};
230 }
231  
232 $search_opts = {
233 0 page => 1,
234 %$search_opts,
235 };
236  
237 0 ▶ if( !defined $opts ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts) 0 0 0
238 0 $opts = {
239 maxResults => 100,
240 };
241 }
242  
243 0 my $url = URI->new( $self->{ api_file_url } );
244 0 $opts->{ q } = "'$folder_id' in parents";
245  
246 0 ▶ if( $search_opts->{ title } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search_opts->{"title"}) 0 0 0
247 0 $opts->{ q } .= " AND title = '$search_opts->{ title }'";
248 }
249  
250 0 my @children = ();
251  
252 0 while( 1 ) {
253 0 $url->query_form( $opts );
254  
255 0 my $data = $self->http_json( $url );
256 0 my $next_item = $self->item_iterator( $data );
257  
258 0 ▶ while( my $item = $next_item->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = &$next_item()) 0 0 0
259 0 push @children, $self->data_factory( $item );
260 }
261  
262 0 ▶ if( $search_opts->{ page } and $data->{ nextPageToken } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search_opts->{'page'} and $data->{'nextPageToken'}) { } 0 0 0
Condition0%0/3
$search_opts->{"page"} and $data->{"nextPageToken"}
!ll&&!rl&&r
000
MC/DC0%0/2
$search_opts->{"page"} and $data->{"nextPageToken"}
$search_opts->{"page"} $data->{"nextPageToken"}
Truth table0%0/3
A and B
A= $search_opts->{"page"}B= $data->{"nextPageToken"}
ABresult
0X0
100
111
263 0 $opts->{ pageToken } = $data->{ nextPageToken };
264 } else {
265 0 last;
266 }
267 }
268  
269 0 return \@children;
270 }
271  
272 ###########################################
273 sub children {
274 ###########################################
275 0 ▶ my( $self, $path, $opts, $search_opts ) = @_;
Subroutine children: not called CC=7 SCAR=40.3
Pod documented
276  
277 0 DEBUG "Determine children of $path";
278  
279 0 ▶ if( !defined $path ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path) 0 0 0
280 0 LOGDIE "No $path given";
281 }
282  
283 0 ▶ if( !defined $search_opts ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $search_opts) 0 0 0
284 0 $search_opts = {};
285 }
286  
287 0 my @parts = split '/', $path;
288 0 my $parent = $parts[0] = "root";
289 0 DEBUG "Parent: $parent";
290  
291 0 my $folder_id = shift @parts;
292  
293 0 PART: for my $part ( @parts ) {
294  
295 0 DEBUG "Looking up part $part (folder_id=$folder_id)";
296  
297 0 my $children = $self->children_by_folder_id( $folder_id,
298 { maxResults => 100, # path resolution maxResults is different
299 },
300 { %$search_opts, title => $part },
301 );
302  
303 0 for my $child ( @$children ) {
304 0 DEBUG "Found child ", $child->title();
305 0 ▶ if( $child->title() eq $part ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($child->title eq $part) 0 0 0
306 0 $folder_id = $child->id();
307 0 $parent = $folder_id;
308 0 DEBUG "Parent: $parent";
309 0 next PART;
310 }
311 }
312  
313 0 LOGDIE "Child $part not found";
314 }
315  
316 0 DEBUG "Getting content of folder $folder_id";
317  
318 0 my $children = $self->children_by_folder_id( $folder_id, $opts,
319 $search_opts );
320  
321 0 ▶ if( wantarray ) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
322 0 return( $children, $parent );
323 } else {
324 0 return $children;
325 }
326 }
327  
328 ###########################################
329 sub search {
330 ###########################################
331 0 ▶ my( $self, $opts, $search_opts, $query ) = @_;
Subroutine search: not called CC=6 SCAR=37.4
Pod documented
332 0 ▶ $search_opts||= { page => 1 };
Condition0%0/2
$search_opts ||= {"page", 1}
l!l
00
MC/DC0%0/1
$search_opts ||= {"page", 1}
$search_opts
Truth table0%0/2
A
A= $search_opts
Aresult
11
00
333  
334 0 $self->init();
335  
336 0 ▶ if( !defined $opts ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts) 0 0 0
337 0 $opts = {
338 maxResults => 100,
339 };
340 }
341  
342 0 my $url = URI->new( $self->{ api_file_url } );
343  
344 0 $opts->{ q }= $query;
345  
346 0 my @children = ();
347  
348 0 while( 1 ) {
349 0 $url->query_form( $opts );
350  
351 0 my $data = $self->http_json( $url );
352 0 my $next_item = $self->item_iterator( $data );
353  
354 0 ▶ while( my $item = $next_item->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = &$next_item()) 0 0 0
355 0 push @children, $self->data_factory( $item );
356 }
357  
358 0 ▶ if( $search_opts->{ page } and $data->{ nextPageToken } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search_opts->{'page'} and $data->{'nextPageToken'}) { } 0 0 0
Condition0%0/3
$search_opts->{"page"} and $data->{"nextPageToken"}
!ll&&!rl&&r
000
MC/DC0%0/2
$search_opts->{"page"} and $data->{"nextPageToken"}
$search_opts->{"page"} $data->{"nextPageToken"}
Truth table0%0/3
A and B
A= $search_opts->{"page"}B= $data->{"nextPageToken"}
ABresult
0X0
100
111
359 0 $opts->{ pageToken } = $data->{ nextPageToken };
360 } else {
361 0 last;
362 }
363 }
364  
365 0 return \@children;
366 }
367  
368 ###########################################
369 sub data_factory {
370 ###########################################
371 0 ▶ my( $self, $data ) = @_;
Subroutine data_factory: not called CC=2 SCAR=17.9
Pod undocumented
372  
373 0 my $mock = Test::MockObject->new();
374  
375 0 for my $key ( keys %$data ) {
376 # DEBUG "Adding method $key";
377 0 ▶ $mock->mock( $key , sub { $data->{ $key } } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
378 }
379  
380 0 return $mock;
381 }
382  
383 ###########################################
384 sub download {
385 ###########################################
386 0 ▶ my( $self, $url, $local_file ) = @_;
Subroutine download: not called CC=4 SCAR=30.0
Pod documented
387  
388 0 ▶ if( ref $url ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $url) 0 0 0
389 0 $url = $url->downloadUrl();
390 }
391  
392 0 my $req = HTTP::Request->new(
393 GET => $url,
394 );
395 0 $req->header( $self->{ oauth }->authorization_headers() );
396  
397 0 my $ua = LWP::UserAgent->new();
398 0 my $resp = $ua->request( $req, $local_file );
399  
400 0 ▶ if( $resp->is_error() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_error) 0 0 0
401 0 warn "Can't download $url ($!)";
402 0 return undef;
403 }
404  
405 0 ▶ if( $local_file ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($local_file) 0 0 0
406 0 return 1;
407 }
408  
409 0 return $resp->content();
410 }
411  
412  
413 ###########################################
414 sub http_loop {
415 ###########################################
416 0 ▶ my( $self, $req, $noinit ) = @_;
Subroutine http_loop: not called CC=4 SCAR=30.0
Pod undocumented
417  
418 0 my $ua = LWP::UserAgent->new();
419 0 my $resp;
420  
421 0 my $RETRIES = 3;
422 0 my $SLEEP_INTERVAL = 10;
423  
424 {
425 # refresh token if necessary
426 0 ▶ if( ! $noinit ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($noinit) 0 0 0
427 0 $self->init();
428 }
429  
430 0 DEBUG "Fetching ", $req->url->as_string();
431  
432 0 $resp = $ua->request( $req );
433  
434 0 ▶ if( ! $resp->is_success() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($resp->is_success) 0 0 0
435 0 warn "Failed with ", $resp->code(), ": ", $resp->message();
436 0 ▶ if( --$RETRIES >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (--$RETRIES >= 0) { } 0 0 0
437 0 ERROR "Retrying in $SLEEP_INTERVAL seconds";
438 0 sleep $SLEEP_INTERVAL;
439 0 redo;
440 } else {
441 0 die "Out of retries.";
442 }
443 }
444  
445 0 DEBUG "Successfully fetched ", length( $resp->content() ), " bytes.";
446 }
447  
448 0 return $resp;
449 }
450  
451 ###########################################
452 sub http_json {
453 ###########################################
454 0 ▶ my( $self, $url, $post_data ) = @_;
Subroutine http_json: not called CC=2 SCAR=17.9
Pod undocumented
455  
456 0 my $req;
457  
458 0 ▶ if( $post_data ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($post_data) { } 0 0 0
459 $req = &HTTP::Request::Common::POST(
460 $url->as_string,
461 0 $self->{ oauth }->authorization_headers(),
462 "Content-Type"=> "application/json",
463 Content => to_json( $post_data ),
464 );
465 } else {
466 0 $req = HTTP::Request->new(
467 GET => $url->as_string,
468 );
469 0 $req->header( $self->{ oauth }->authorization_headers() );
470 }
471  
472 0 my $resp = $self->http_loop( $req );
473  
474 0 my $data = from_json( $resp->content() );
475  
476 0 return $data;
477 }
478  
479 ###########################################
480 sub file_mime_type {
481 ###########################################
482 0 ▶ my( $self, $file ) = @_;
Subroutine file_mime_type: not called CC=2 SCAR=17.9
Pod undocumented
483  
484 # There don't seem to be great implementations of mimetype
485 # detection on CPAN, so just use this one for now.
486  
487 0 ▶ if( !$self->{ magic } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"magic"}) 0 0 0
488 0 $self->{ magic } = File::MMagic->new();
489 }
490  
491 0 return $self->{ magic }->checktype_filename( $file );
492 }
493  
494 ###########################################
495 sub item_iterator {
496 ###########################################
497 0 ▶ my( $self, $data ) = @_;
Subroutine item_iterator: not called CC=2 SCAR=17.9
Pod undocumented
498  
499 0 my $idx = 0;
500  
501 0 ▶ if( !defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 0 0 0
502 0 die "no data in item_iterator";
503 }
504  
505 return sub {
506 {
507 0 ▶ my $next_item = $data->{ items }->[ $idx++ ];
Subroutine __ANON__: not called CC=3 SCAR=24.8
508  
509 0 ▶ return if !defined $next_item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $next_item 0 0 0
510  
511 0 ▶ if( $next_item->{ labels }->{ trashed } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($next_item->{"labels"}{"trashed"}) 0 0 0
512 0 DEBUG "Skipping $next_item->{ title } (trashed)";
513 0 redo;
514 }
515  
516 0 return $next_item;
517 }
518 0 };
519 }
520  
521 1 1;
522  
523 __END__
524  
525 =head1 NAME
526  
527 Net::Google::Drive::Simple - Simple modification of Google Drive data
528  
529 =head1 SYNOPSIS
530  
531 use Net::Google::Drive::Simple;
532  
533 # requires a ~/.google-drive.yml file with an access token,
534 # see description below.
535 my $gd = Net::Google::Drive::Simple->new();
536  
537 my $children = $gd->children( "/folder/path" );
538  
539 for my $child ( @$children ) {
540  
541 next if $child->kind() ne 'drive#file';
542  
543 next if !$child->can( "downloadUrl" );
544  
545 print $child->originalFilename(),
546 " can be downloaded at ",
547 $child->downloadUrl(),
548 "\n";
549 }
550  
551 =head1 DESCRIPTION
552  
553 Net::Google::Drive::Simple authenticates with a user's Google Drive and
554 offers several convenience methods to list, retrieve, and modify the data
555 stored in the 'cloud'. See C<eg/google-drive-upsync> as an example on how
556 to keep a local directory in sync with a remote directory on Google Drive.
557  
558 =head2 GETTING STARTED
559  
560 To get the access token required to access your Google Drive data via
561 this module, you need to run the script C<eg/google-drive-init> in this
562 distribution.
563  
564 Before you run it, you need to register your 'app' with Google Drive
565 and obtain a client_id and a client_secret from Google:
566  
567 https://developers.google.com/drive/web/enable-sdk
568  
569 Click on "Enable the Drive API and SDK", and find "Create an API project in
570 the Google APIs Console". On the API console, create a new project, click
571 "Services", and enable "Drive API" (leave "drive SDK" off). Then, under
572 "API Access" in the navigation bar, create a client ID, and make sure to
573 register a an "installed application" (not a "web application"). "Redirect
574 URIs" should contain "http://localhost". This will get you a "Client ID"
575 and a "Client Secret".
576  
577 Then, replace the following lines in C<eg/google-drive-init> with the
578 values received:
579  
580 # You need to obtain a client_id and a client_secret from
581 # https://developers.google.com/drive to use this.
582 my $client_id = "XXX";
583 my $client_secret = "YYY";
584  
585 Then run the script. It'll start a web server on port 8082 on your local
586 machine. When you point your browser at http://localhost:8082, you'll see a
587 link that will lead you to Google Drive's login page, where you authenticate
588 and then allow the app (specified by client_id and client_secret above) access
589 to your Google Drive data. The script will then receive an access token from
590 Google Drive and store it in ~/.google-drive.yml from where other scripts can
591 pick it up and work on the data stored on the user's Google Drive account. Make
592 sure to limit access to ~/.google-drive.yml, because it contains the access
593 token that allows everyone to manipulate your Google Drive data. It also
594 contains a refresh token that this library uses to get a new access token
595 transparently when the old one is about to expire.
596  
597 =head1 METHODS
598  
599 =over 4
600  
601 =item C<new()>
602  
603 Constructor, creates a helper object to retrieve Google Drive data
604 later. Takes an optional name of the C<.google-drive.yml> file
605  
606 my $gd = Net::Google::Drive::Simple->new(
607 config_file => "gd.yml",
608 );
609  
610 or uses C<~/.google-drive.yml> in the user's home directory as default.
611  
612 =item C<my $children = $gd-E<gt>children( "/path/to" )>
613  
614 Return the entries under a given path on the Google Drive as a reference
615 to an array. Each entry
616 is an object composed of the JSON data returned by the Google Drive API.
617 Each object offers methods named like the fields in the JSON data, e.g.
618 C<originalFilename()>, C<downloadUrl>, etc.
619  
620 Will return all entries found unless C<maxResults> is set:
621  
622 my $children = $gd->children( "/path/to", { maxResults => 3 } )
623  
624 Due to the somewhat capricious ways Google Drive handles its directory
625 structures, the method needs to traverse the path component by component
626 and determine the ID of each directory to get to the next level. To speed
627 up subsequent lookups, it also returns the ID of the last component to the
628 caller:
629  
630 my( $children, $parent ) = $gd->children( "/path/to" );
631  
632 If the caller now wants to e.g. insert a file into the directory, its
633 ID is available in $parent.
634  
635 Each child comes back as a files#resource type and gets mapped into
636 an object that offers access to the various fields via methods:
637  
638 for my $child ( @$children ) {
639 print $child->kind(), " ", $child->title(), "\n";
640 }
641  
642 Please refer to
643  
644 https://developers.google.com/drive/v2/reference/files#resource
645  
646 for details on which fields are available.
647  
648 =item C<my $files = $gd-E<gt>files( )>
649  
650 Return all files on the drive as a reference to an array.
651 Will return all entries found unless C<maxResults> is set:
652  
653 my $files = $gd->files( { maxResults => 3 } )
654  
655 Note that Google limits the number of entries returned by default to
656 100, and seems to restrict the maximum number of files returned
657 by a single query to 3,500, even if you specify higher values for
658 C<maxResults>.
659  
660 Each file comes back as an object that offers access to the Google
661 Drive item's fields, according to the API (see C<children()>).
662  
663 =item C<my $id = $gd-E<gt>folder_create( "folder-name", $parent_id )>
664  
665 Create a new folder as a child of the folder with the id C<$parent_id>.
666 Returns the ID of the new folder or undef in case of an error.
667  
668 =item C<$gd-E<gt>file_upload( $file, $dir_id )>
669  
670 Uploads the content of the file C<$file> into the directory with the ID
671 $dir_id on Google Drive. Uses C<$file> as the file name.
672  
673 To overwrite an existing file on Google Drive, specify the file's ID as
674 an optional parameter:
675  
676 $gd->file_upload( $file, $dir_id, $file_id );
677  
678 =item C<$gd-E<gt>download( $item, [$local_filename] )>
679  
680 Downloads an item found via C<files()> or C<children()>. Also accepts
681 the downloadUrl of an item. If C<$local_filename> is not specified,
682 C<download()> will return the data downloaded (this might be undesirable
683 for large files). If C<$local_filename> is specified, C<download()> will
684 store the downloaded data under the given file name.
685  
686 my $gd = Net::Google::Drive::Simple->new();
687 my $files = $gd->files( { maxResults => 20 }, { page => 0 } );
688 for my $file ( @$files ) {
689 my $name = $file->originalFilename();
690 print "Downloading $name\n";
691 $gd->download( $file, $name ) or die "failed: $!";
692 }
693  
694 Be aware that only documents like PDF or png can be downloaded directly. Google Drive Documents like spreadsheets or (text) documents need to be exported into one of the available formats.
695 Check for "exportLinks" on a file given. In case of a document that can be exported you will receive a hash in the form:
696  
697 {
698 'format_1' => 'download_link_1',
699 'format_2' => 'download_link_2',
700 ...
701 }
702  
703 Choose your download link and use it as an argument to the download() function which can also take urls directly.
704  
705 my $gd = Net::Google::Drive::Simple->new();
706 my $children = $gd->children( '/path/to/folder/on/google/drive' );
707 for my $child ( @$children ) {
708 if ($child->can( 'exportLinks' )){
709 my $type_chosen;
710 foreach my $type (keys %{$child->exportLinks()}){
711 # Take any type you can get..
712 $type_chosen = $type;
713 # ..but choose your preferred format, opendocument here:
714 last if $type =~/oasis\.opendocument/;
715 }
716 my $url = $child->exportLinks()->{$type_chosen};
717  
718 $gd->download($url, 'my/local/file');
719  
720 }
721 }
722  
723 =item C<my $files = $gd-E<gt>search( )>
724  
725 my $children= $gd->search({ maxResults => 20 },{ page => 0 },
726 "title contains 'Futurama'");
727  
728 Search files for attributes. See
729 L<https://developers.google.com/drive/web/search-parameters>
730 for a definition of the attributes.
731  
732 To list all available files, those on the drive, those directly shared
733 with the user, and those generally available to the user, use an
734 empty search:
735  
736 my $children= $gd->search({},{ page => 0 },"");
737  
738 =back
739  
740 =head1 LOGGING/DEBUGGING
741  
742 Net::Google::Drive::Simple is Log4perl-enabled.
743 To find out what's going on under the hood, turn on Log4perl:
744  
745 use Log::Log4perl qw(:easy);
746 Log::Log4perl->easy_init($DEBUG);
747  
748 =head1 LEGALESE
749  
750 Copyright 2012 by Mike Schilli, all rights reserved.
751 This program is free software, you can redistribute it and/or
752 modify it under the same terms as Perl itself.
753  
754 =head1 AUTHOR
755  
756 2012, Mike Schilli <cpan@perlmeister.com>
↑ Summary