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

filter: Statementstmt 0.0% 0 / 230 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 45 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 354 CC 20 SCAR 23.4
CC
20
Cov
0%
uploadFile
30.0
downloadFile
20.0
setFilePermission
20.0
CRAP 10.3
1 package Net::Google::Drive;
2  
3 use 5.008001;
4 use strict;
5 use warnings;
6 use utf8;
7  
8 use lib '/home/vrag/perl/googleoauth/lib';
9  
10 use LWP::UserAgent;
11 use HTTP::Request;
12 use JSON::XS;
13 use URI;
14 use File::Basename;
15  
16 use Carp qw/carp croak/;
17  
18 use Net::Google::OAuth;
19  
20 use Data::Printer;
21  
22 our $VERSION = '0.01';
23  
24 our $DOWNLOAD_BUFF_SIZE = 1024;
25 our $UPLOAD_BUFF_SIZE = 256 * 1024;
26 our $FILE_API_URL = 'https://www.googleapis.com/drive/v3/files';
27 our $FILE_API2_URL = 'https://www.googleapis.com/drive/v2/files';
28 our $UPLOAD_FILE_API_URL = 'https://www.googleapis.com/upload/drive/v3/files';
29  
30 sub new {
31 my ($class, %opt) = @_;
32  
33 my $self = {};
34 my $client_id = $opt{-client_id} // croak "You must specify '-client_id' param";
35 my $client_secret = $opt{-client_secret} // croak "You must specify '-client_secret' param";
36 $self->{access_token} = $opt{-access_token} // croak "You must specify '-access_token' param";
37 $self->{refresh_token} = $opt{-refresh_token} // croak "You must specify '-refresh_token' param";
38 $self->{ua} = LWP::UserAgent->new();
39  
40 $self->{oauth} = Net::Google::OAuth->new(
41 -client_id => $client_id,
42 -client_secret => $client_secret,
43 );
44 bless $self, $class;
45 return $self;
46 }
47  
48 sub searchFileByName {
49 my ($self, %opt) = @_;
50 my $filename = $opt{-filename} || croak "You must specify '-filename' param";
51  
52 my $search_res = $self->__searchFile('name=\'' . $filename . "'");
53
54 return $search_res;
55 }
56  
57 sub searchFileByNameContains {
58 my ($self, %opt) = @_;
59 my $filename = $opt{-filename} || croak "You must specify '-filename' param";
60  
61 my $search_res = $self->__searchFile('name contains \'' . $filename . "'");
62
63 return $search_res;
64 }
65  
66  
67 sub downloadFile {
68 my ($self, %opt) = @_;
69 my $file_id = $opt{-file_id} || croak "You must specify '-file_id' param";
70 my $dest_file = $opt{-dest_file} || croak "You must specify '-dest_file' param";
71 my $ua = $self->{ua};
72 my $access_token = $self->__getAccessToken();
73  
74 my $uri = URI->new(join('/', $FILE_API_URL, $file_id));
75 $uri->query_form(
76 'alt' => 'media',
77 );
78 my $headers = [
79 'Authorization' => 'Bearer ' . $access_token,
80 ];
81  
82 my $request = HTTP::Request->new( 'GET',
83 $uri,
84 $headers,
85 );
86  
87 my $FL;
88 my $response = $ua->request($request, sub {
89 if (not $FL) {
90 open $FL, ">$dest_file" or croak "Cant open $dest_file to write $!";
91 binmode $FL;
92 }
93 print $FL $_[0];
94 },
95 $DOWNLOAD_BUFF_SIZE
96 );
97 if ($FL) {
98 close $FL;
99 }
100 my $response_code = $response->code();
101 if ($response_code != 200) {
102 my $error_message = __readErrorMessageFromResponse($response);
103 croak "Can't download file id: $file_id to destination file: $dest_file. Code: $response_code. Message: '$error_message'";
104 }
105 return 1;
106 }
107  
108 sub deleteFile {
109 my ($self, %opt) = @_;
110 my $file_id = $opt{-file_id} || croak "You must specify '-file_id' param";
111 my $access_token = $self->__getAccessToken();
112  
113 my $uri = URI->new(join('/', $FILE_API_URL, $file_id));
114  
115 my $headers = [
116 'Authorization' => 'Bearer ' . $access_token,
117 ];
118  
119 my $request = HTTP::Request->new( 'DELETE',
120 $uri,
121 $headers,
122 );
123 my $response = $self->{ua}->request($request);
124 my $response_code = $response->code();
125 if ($response_code =~ /^[^2]/) {
126 my $error_message = __readErrorMessageFromResponse($response);
127 croak "Can't delete file id: $file_id. Code: $response_code. Message: $error_message";
128 }
129 return 1;
130 }
131  
132 sub uploadFile {
133 my ($self, %opt) = @_;
134 my $source_file = $opt{-source_file} || croak "You must specify '-source_file' param";
135  
136 if (not -f $source_file) {
137 croak "File: $source_file not exists";
138 }
139  
140 my $file_size = (stat $source_file)[7];
141 my $part_upload_uri = $self->__createEmptyFile($source_file, $file_size);
142 open my $FH, "<$source_file" or croak "Can't open file: $source_file $!";
143 binmode $FH;
144  
145 my $filebuf;
146 my $uri = URI->new($part_upload_uri);
147 my $start_byte = 0;
148 while (my $bytes = read($FH, $filebuf, $UPLOAD_BUFF_SIZE)) {
149 my $end_byte = $start_byte + $bytes - 1;
150 my $headers = [
151 'Content-Length' => $bytes,
152 'Content-Range' => sprintf("bytes %d-%d/%d", $start_byte, $end_byte, $file_size),
153 ];
154 my $request = HTTP::Request->new('PUT', $uri, $headers, $filebuf);
155  
156 # Send request to upload part of file
157 my $response = $self->{ua}->request($request);
158 my $response_code = $response->code();
159 # On end part, response code is 200, on middle part is 308
160 if ($response_code == 200 || $response_code == 201) {
161 if ($end_byte + 1 != $file_size) {
162 croak "Server return code: $response_code on upload file, but file is not fully uploaded. End byte: $end_byte. File size: $file_size. File: $source_file";
163 }
164 return decode_json($response->content());
165 }
166 elsif ($response_code != 308) {
167 croak "Wrong response code on upload part file. Code: $response_code. File: $source_file";
168 }
169 $start_byte += $bytes;
170 }
171 close $FH;
172  
173 return;
174 }
175  
176 sub setFilePermission {
177 my ($self, %opt) = @_;
178 my $file_id = $opt{-file_id} || croak "You must specify '-file_id' param";
179 my $permission_type = $opt{-type} || croak "You must specify '-type' param";
180 my $role = $opt{-role} || croak "You must specify '-role' param";
181 my %valid_permissions = (
182 'user' => 1,
183 'group' => 1,
184 'domain' => 1,
185 'anyone' => 1,
186 );
187  
188 my %valid_roles = (
189 'owner' => 1,
190 'organizer' => 1,
191 'fileOrganizer' => 1,
192 'writer' => 1,
193 'commenter' => 1,
194 'reader' => 1,
195 );
196 #Check permission in param
197 if (not $valid_permissions{$permission_type}) {
198 croak "Wrong permission type: '$permission_type'. Valid permissions types: " . join(' ', keys %valid_permissions);
199 }
200  
201 #Check role in param
202 if (not $valid_roles{$role}) {
203 croak "Wrong role: '$role'. Valid roles: " . join(' ', keys %valid_roles);
204 }
205 my $access_token = $self->__getAccessToken();
206  
207 my $uri = URI->new(join('/', $FILE_API_URL, $file_id, 'permissions'));
208 my $headers = [
209 'Authorization' => 'Bearer ' . $access_token,
210 'Content-Type' => 'application/json',
211 ];
212 my $request_content = {
213 'type' => $permission_type,
214 'role' => $role,
215 };
216  
217 my $request = HTTP::Request->new('POST', $uri, $headers, encode_json($request_content));
218  
219 my $response = $self->{ua}->request($request);
220 my $response_code = $response->code();
221 if ($response_code != 200) {
222 my $error_message = __readErrorMessageFromResponse($response);
223 croak "Can't share file id: $file_id. Code: $response_code. Error message: $error_message";
224 }
225 return decode_json($response->content());
226 }
227  
228 sub getFileMetadata {
229 my ($self, %opt) = @_;
230 my $file_id = $opt{-file_id} || croak "You must specify '-file_id' param";
231 my $access_token = $self->__getAccessToken();
232  
233 my $uri = URI->new(join('/', $FILE_API2_URL, $file_id));
234 $uri->query_form('supportsTeamDrives' => 'true');
235  
236 my $headers = [
237 'Authorization' => 'Bearer ' . $access_token,
238 ];
239 my $request = HTTP::Request->new("GET", $uri, $headers);
240 my $response = $self->{ua}->request($request);
241 my $response_code = $response->code();
242 if ($response_code != 200) {
243 my $error_message = __readErrorMessageFromResponse($response);
244 croak "Can't get metadata from file id: $file_id. Code: $response_code. Error message: $error_message";
245 }
246 return decode_json($response->content());
247 }
248  
249 sub shareFile {
250 my ($self, %opt) = @_;
251 my $file_id = $opt{-file_id} || croak "You must specify '-file_id' param";
252  
253 ## Adding permissions to file
254 my $permission = $self->setFilePermission(
255 -file_id => $file_id,
256 -type => 'anyone',
257 -role => 'reader',
258 );
259 if ((not exists $permission->{type}) || ($permission->{type} ne 'anyone')) {
260 croak "Can't set permission to anyone for file id: $file_id";
261 }
262  
263 my $metadata = $self->getFileMetadata( -file_id => $file_id );
264 return $metadata->{webContentLink};
265 }
266  
267 sub __createEmptyFile {
268 my ($self, $source_file, $file_size) = @_;
269 my $access_token = $self->__getAccessToken();
270  
271 my $body = {
272 'name' => basename($source_file),
273 };
274 my $body_json = encode_json($body);
275  
276 my $uri = URI->new($UPLOAD_FILE_API_URL);
277 $uri->query_form('upload_type' => 'resumable');
278 my $headers = [
279 'Authorization' => 'Bearer ' . $access_token,
280 'Content-Length' => length($body_json),
281 'Content-Type' => 'application/json; charset=UTF-8',
282 'X-Upload-Content-Length' => $file_size,
283 ];
284  
285 my $request = HTTP::Request->new('POST', $uri, $headers, $body_json);
286 my $response = $self->{ua}->request($request);
287  
288 my $response_code = $response->code();
289 if ($response_code != 200) {
290 my $error_message = __readErrorMessageFromResponse($response);
291 croak "Can't upload part of file. Code: $response_code. Error message: $error_message";
292 }
293  
294 my $location = $response->header('Location') or croak "Location header not defined";
295  
296 return $location;
297 }
298  
299 sub __readErrorMessageFromResponse {
300 my ($response) = @_;
301 my $error_message = eval {decode_json($response->content)};
302 if ($error_message) {
303 return $error_message->{error}->{message};
304 }
305 return '';
306 }
307  
308  
309  
310 sub __searchFile {
311 my ($self, $q) = @_;
312  
313 my $access_token = $self->__getAccessToken();
314
315 my $headers = [
316 'Authorization' => 'Bearer ' . $access_token,
317 ];
318  
319 my $uri = URI->new($FILE_API_URL);
320 $uri->query_form('q' => $q);
321 my $request = HTTP::Request->new('GET',
322 $uri,
323 $headers,
324 );
325 my $files = [];
326 $self->__apiRequest($request, $files);
327  
328  
329 return $files;
330 }
331  
332 sub __apiRequest {
333 my ($self, $request, $files) = @_;
334  
335 my $response = $self->{ua}->request($request);
336 my $response_code = $response->code;
337 if ($response_code != 200) {
338 croak "Wrong response code on search_file. Code: $response_code";
339 }
340  
341 my $json_res = decode_json($response->content);
342  
343 if (my $next_token = $json_res->{next_token}) {
344 my $uri = $request->uri;
345 $uri->query_form('next_token' => $next_token);
346 $self->__apiRequest($request, $files);
347 }
348 push @$files, @{$json_res->{files}};
349  
350 return 1;
351 }
352  
353 sub __getAccessToken {
354 my ($self) = @_;
355  
356 my $oauth = $self->{oauth};
357 my $token_info =
358 eval {
359 $oauth->getTokenInfo( -access_token => $self->{access_token} );
360 };
361 # If error on get token info or token is expired
362 if (not $@) {
363 if ((exists $token_info->{expires_in}) && ($token_info->{expires_in} > 5)) {
364 return $self->{access_token};
365 }
366 }
367  
368 #Refresh token
369 $oauth->refreshToken( -refresh_token => $self->{refresh_token} );
370 $self->{refresh_token} = $oauth->getRefreshToken();
371 $self->{access_token} = $oauth->getAccessToken();
372  
373 return $self->{access_token};
374 }
375  
376 1;
377  
378 =head1 NAME
379  
380 B<Net::Google::Drive> - simple Google drive API module
381  
382 =head1 SYNOPSIS
383  
384 This module use to upload, download, share file on Google drive
385 use Net::Google::Drive;
386  
387 #Create disk object. You need send in param 'access_token', 'refresh_token', 'client_id' and 'client_secret'.
388 #Values of 'client_id' and 'client_secret' uses to create Net::Google::OAuth object so that update value of 'access_token'.
389 my $disk = Net::Google::Drive->new(
390 -client_id => $client_id,
391 -client_secret => $client_secret,
392 -access_token => $access_token,
393 -refresh_token => $refresh_token,
394 );
395  
396 # Search file by name
397 my $file_name = 'upload.doc';
398 my $files = $drive->searchFileByName( -filename => $file_name ) or croak "File '$file_name' not found";
399 my $file_id = $files->[0]->{id};
400 print "File id: $file_id\n";
401  
402 #Download file
403 my $dest_file = '/home/upload.doc';
404 $disk->downloadFile(
405 -file_id => $file_id,
406 -dest_file => $dest_file,
407 );
408  
409 #Upload file
410 my $source_file = '/home/upload.doc';
411 my $res = $disk->uploadFile( -source_file => $source_file );
412 print "File: $source_file uploaded. File id: $res->{id}\n";
413  
414 =head1 METHODS
415  
416 =head2 new(%opt)
417  
418 Create L<Net::Google::Disk> object
419  
420 %opt:
421 -client_id => Your app client id (Get from google when register your app)
422 -client_secret => Your app client secret (Get from google when register your app)
423 -access_token => Access token value (Get from L<Net::Google::OAuth>)
424 -refresh_token => Refresh token value (Get from L<Net::Google::OAuth>)
425  
426 =head2 searchFileByName(%opt)
427  
428 Search file on google disk by name. Return arrayref to info with found files. If files not found - return empty arrayref
429  
430 %opt:
431 -filename => Name of file to find
432 Return:
433 [
434 [0] {
435 id "1f13sLfo6UEyUuFpn-NWPnY",
436 kind "drive#file",
437 mimeType "application/x-perl",
438 name "drive.t"
439 }
440 ]
441
442 =head2 searchFileByNameContains(%opt)
443  
444 Search files on google drive by name contains value in param '-filename'
445 Param and return value same as in method L<searchFileByName>
446  
447 =head2 downloadFile(%opt)
448  
449 Download file from google dist to -dest_file on local system. Return 1 if success, die in otherwise
450  
451 %opt:
452 -dest_file => Name of file on disk in which you will download file from google disk
453 -file_id => Id of file on google disk
454  
455 =head2 deleteFile(%opt)
456  
457 Delete file from google disk. Return 1 if success, die in otherwise
458  
459 %opt:
460 -file_id => Id of file on google disk
461  
462 =head2 uploadFile(%opt)
463  
464 Upload file from local system to google drive. Return file_info hashref if success, die in otherwise
465
466 %opt:
467 -source_file => File on local system
468 Return:
469 {
470 id "1LVAr2PpqX9m314JyZ6YJ4v_KIzG0Gey2",
471 kind "drive#file",
472 mimeType "application/octet-stream",
473 name "gogle_upload_file"
474 }
475  
476 =head2 setFilePermission(%opt)
477  
478 Set permissions for file on google drive. Return permission hashref, die in otherwise
479  
480 %opt:
481 -file_id => Id of file on google disk
482 -type => The type of the grantee. Valid values are: (user, group, domain, anyone)
483 -role => The role granted by this permission. Valid values are: (owner, organizer, fileOrganizer, writer, commenter, reader)
484 Return:
485 {
486 allowFileDiscovery JSON::PP::Boolean {
487 Parents Types::Serialiser::BooleanBase
488 public methods (0)
489 private methods (0)
490 internals: 0
491 },
492 id "anyoneWithLink",
493 kind "drive#permission",
494 role "reader",
495 type "anyone"
496 }
497  
498 =head2 getFileMetadata(%opt)
499  
500 Get metadata of file. Return hashref with metadata if success, die in otherwise
501  
502 %opt:
503 -file_id => Id of file on google disk
504 Return:
505 { alternateLink "https://drive.google.com/file/d/10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut/view?usp=drivesdk",
506 appDataContents JSON::PP::Boolean {
507 Parents Types::Serialiser::BooleanBase
508 public methods (0)
509 private methods (0)
510 internals: 0
511 },
512 capabilities {
513 canCopy JSON::PP::Boolean {
514 Parents Types::Serialiser::BooleanBase
515 public methods (0)
516 private methods (0)
517 internals: 1
518 },
519 canEdit var{capabilities}{canCopy}
520 },
521 copyable var{capabilities}{canCopy},
522 copyRequiresWriterPermission var{appDataContents},
523 createdDate "2018-10-04T12:05:15.896Z",
524 downloadUrl "https://doc-0g-7o-docs.googleusercontent.com/docs/securesc/ck8i7vfbvef13kb30b8mkrcjv4ihp2uj/3mfn1kbr655euhlo7tctg5mmn8oirg
525 gf/1538654400000/10526805100525201667/10526805100525201667/10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut?e=download&gd=true",
526 editable var{capabilities}{canCopy},
527 embedLink "https://drive.google.com/file/d/10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut/preview?usp=drivesdk",
528 etag ""omwGuTP8OdxhZkubyp-j43cFdJQ/MTUzODY1NDcxNTg5Ng"",
529 explicitlyTrashed var{appDataContents},
530 fileExtension "",
531 fileSize 1000000,
532 headRevisionId "0B4HgPHxdPy22UmZXSFVRTkRLbXhFakdzZjFSUGkrNWZIVFN3PQ",
533 iconLink "https://drive-thirdparty.googleusercontent.com/16/type/application/octet-stream",
534 id "10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut",
535 kind "drive#file",
536 labels {
537 hidden var{appDataContents},
538 restricted var{appDataContents},
539 starred var{appDataContents},
540 trashed var{appDataContents},
541 viewed var{appDataContents}
542 },
543 lastModifyingUser {
544 displayName "Ларри Уолл",
545 emailAddress "perlgogledrivemodule@gmail.com",
546 isAuthenticatedUser var{capabilities}{canCopy},
547 kind "drive#user",
548 permissionId 10526805100525201667
549 },
550 lastModifyingUserName "Ларри Уолл",
551 markedViewedByMeDate "1970-01-01T00:00:00.000Z",
552 md5Checksum "ded2a2983b3e1743152d8224549510e1",
553 mimeType "application/octet-stream",
554 modifiedByMeDate "2018-10-04T12:05:15.896Z",
555 modifiedDate "2018-10-04T12:05:15.896Z",
556 originalFilename "gogle_upload_file",
557 ownerNames [
558 [0] "Ларри Уолл"
559 ],
560 owners [
561 [0] {
562 displayName "Ларри Уолл",
563 emailAddress "perlgogledrivemodule@gmail.com",
564 isAuthenticatedUser var{capabilities}{canCopy},
565 kind "drive#user",
566 permissionId 10526805100525201667
567 }
568 ],
569 parents [
570 [0] {
571 id "0AIHgPHxdPy22Uk9PVA",
572 isRoot var{capabilities}{canCopy},
573 kind "drive#parentReference",
574 parentLink "https://www.googleapis.com/drive/v2/files/0AIHgPHxdPy22Uk9PVA",
575 selfLink "https://www.googleapis.com/drive/v2/files/10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut/parents/0AIHgPHxdPy22Uk9PVA"
576 }
577 ],
578 quotaBytesUsed 1000000,
579 selfLink "https://www.googleapis.com/drive/v2/files/10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut",
580 shared var{appDataContents},
581 spaces [
582 [0] "drive"
583 ],
584 title "gogle_upload_file",
585 userPermission {
586 etag ""omwGuTP8OdxhZkubyp-j43cFdJQ/N52l-iUAo-dARaTch8nQXOzl348"",
587 id "me",
588 kind "drive#permission",
589 role "owner",
590 selfLink "https://www.googleapis.com/drive/v2/files/10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut/permissions/me",
591 type "user"
592 },
593 version 2,
594 webContentLink "https://drive.google.com/uc?id=10Z5YDCHn3gnj0S4_Lf0poc2Lm5so0Sut&export=download",
595 writersCanShare var{capabilities}{canCopy}
596 }
597  
598 =head2 shareFile(%opt)
599  
600 Share file for download. Return download link if success, die in otherwise
601  
602 %opt:
603 -file_id => Id of file on google disk
604  
605 =head1 DEPENDENCE
606  
607 L<Net::Google::OAuth>, L<LWP::UserAgent>, L<JSON::XS>, L<URI>, L<HTTP::Request>, L<File::Basename>
608  
609 =head1 AUTHORS
610  
611 =over 4
612  
613 =item *
614  
615 Pavel Andryushin <vrag867@gmail.com>
616  
617 =back
618  
619 =head1 COPYRIGHT AND LICENSE
620  
621 This software is copyright (c) 2018 by Pavel Andryushin.
622  
623 This is free software; you can redistribute it and/or modify it under
624 the same terms as the Perl 5 programming language system itself.
625  
626 =cut