| 1 | package Backblaze::B2::v1::AnyEvent; | ||
| 2 | use strict; | ||
| 3 | use JSON::XS; | ||
| 4 | use MIME::Base64; | ||
| 5 | use URI::QueryParam; | ||
| 6 | use Carp qw(croak); | ||
| 7 | |||
| 8 | use Promises | ||
| 9 | backend => ['AnyEvent'], 'deferred'; | ||
| 10 | use AnyEvent; | ||
| 11 | use AnyEvent::HTTP; | ||
| 12 | use URI; | ||
| 13 | use URI::Escape; | ||
| 14 | use Digest::SHA1; | ||
| 15 | use File::Basename; | ||
| 16 | use Encode; | ||
| 17 | use Data::Dumper; | ||
| 18 | |||
| 19 | use vars qw(@CARP_NOT $VERSION); | ||
| 20 | $VERSION = '0.02'; | ||
| 21 | @CARP_NOT = qw(Backblaze::B2::v1::Synchronous); | ||
| 22 | |||
| 23 | sub isAsync { 1 } | ||
| 24 | sub api { $_[0] } | ||
| 25 | sub asyncApi { $_[0] } | ||
| 26 | |||
| 27 | sub new { | ||
| 28 | my( $class, %options ) = @_; | ||
| 29 | |||
| 30 | require Backblaze::B2; | ||
| 31 | |||
| 32 | $options{ api_base } //= $Backblaze::B2::v1::API_BASE | ||
| 33 | = $Backblaze::B2::v1::API_BASE; | ||
| 34 | |||
| 35 | croak "Need an API base" | ||
| 36 | unless $options{ api_base }; | ||
| 37 | |||
| 38 | bless \%options => $class; | ||
| 39 | } | ||
| 40 | |||
| 41 | sub log_message { | ||
| 42 | my( $self ) = shift; | ||
| 43 | if( $self->{log_message}) { | ||
| 44 | goto &{ $self->{log_message}}; | ||
| 45 | }; | ||
| 46 | } | ||
| 47 | |||
| 48 | sub read_credentials { | ||
| 49 | my( $self, $file ) = @_; | ||
| 50 | |||
| 51 | if( ! defined $file) { | ||
| 52 | require File::HomeDir; | ||
| 53 | $file = File::HomeDir->my_home . "/credentials.b2"; | ||
| 54 | $self->log_message(0, "Using default credentials file '$file'"); | ||
| 55 | }; | ||
| 56 | |||
| 57 | $self->log_message(1, "Reading credentials from '$file'"); | ||
| 58 | |||
| 59 | open my $fh, '<', $file | ||
| 60 | or croak "Couldn't read credentials from '$file': $!"; | ||
| 61 | binmode $fh; | ||
| 62 | local $/; | ||
| 63 | my $json = <$fh>; | ||
| 64 | my $cred = decode_json( $json ); | ||
| 65 | |||
| 66 | $self->{credentials} = $cred; | ||
| 67 | |||
| 68 | $cred | ||
| 69 | }; | ||
| 70 | |||
| 71 | sub decode_json_response { | ||
| 72 | my($self, $body,$hdr) = @_; | ||
| 73 | |||
| 74 | $self->log_message(1, sprintf "HTTP Response status %d", $hdr->{Status}); | ||
| 75 | |||
| 76 | my @result; | ||
| 77 | if( !$body) { | ||
| 78 | $self->log_message(4, sprintf "No response body received"); | ||
| 79 | @result = (0, "No response body received", $hdr); | ||
| 80 | } else { | ||
| 81 | |||
| 82 | my $b = eval { decode_json( $body ); }; | ||
| 83 | if( my $err = $@ ) { | ||
| 84 | $self->log_message(4, sprintf "Error decoding JSON response body: %s", $err); | ||
| 85 | @result = (0, sprintf("Error decoding JSON response body: %s", $err), $hdr); | ||
| 86 | } elsif( $hdr->{Status} =~ /^[45]\d\d$/ ) { | ||
| 87 | my $reason = $b->{message} || $hdr->{Reason}; | ||
| 88 | my $status = $b->{status} || $hdr->{Status}; | ||
| 89 | $self->log_message(4, sprintf "HTTP error status: %s: %s", $status, $reason); | ||
| 90 | @result = ( 0, sprintf(sprintf "HTTP error status: %s: %s", $status, $reason)); | ||
| 91 | } else { | ||
| 92 | @result = (1, "", $b); | ||
| 93 | }; | ||
| 94 | }; | ||
| 95 | |||
| 96 | @result | ||
| 97 | } | ||
| 98 | |||
| 99 | # Provide headers from the credentials, if available | ||
| 100 | sub get_headers { | ||
| 101 | my( $self ) = @_; | ||
| 102 | if( my $token = $self->authorizationToken ) { | ||
| 103 | return Authorization => $token | ||
| 104 | }; | ||
| 105 | return () | ||
| 106 | } | ||
| 107 | |||
| 108 | sub accountId { | ||
| 109 | my( $self ) = @_; | ||
| 110 | $self->{credentials}->{accountId} | ||
| 111 | } | ||
| 112 | |||
| 113 | sub authorizationToken { | ||
| 114 | my( $self ) = @_; | ||
| 115 | $self->{credentials}->{authorizationToken} | ||
| 116 | } | ||
| 117 | |||
| 118 | sub downloadUrl { | ||
| 119 | my( $self ) = @_; | ||
| 120 | $self->{credentials}->{downloadUrl} | ||
| 121 | } | ||
| 122 | |||
| 123 | sub apiUrl { | ||
| 124 | my( $self ) = @_; | ||
| 125 | $self->{credentials}->{apiUrl} | ||
| 126 | } | ||
| 127 | |||
| 128 | |||
| 129 | =head2 C<< ->request >> | ||
| 130 | |||
| 131 | Returns a promise that will resolve to the response data and the headers from | ||
| 132 | the request. | ||
| 133 | |||
| 134 | =cut | ||
| 135 | |||
| 136 | # You might want to override this if you want to use HIJK or | ||
| 137 | # some other way. If your HTTP requestor is synchronous, just | ||
| 138 | # return a | ||
| 139 | # AnyEvent->condvar | ||
| 140 | # which performs the real task. | ||
| 141 | # Actually, this now returns just a Promise | ||
| 142 | |||
| 143 | sub request { | ||
| 144 | my( $self, %options) = @_; | ||
| 145 | |||
| 146 | $options{ method } ||= 'GET'; | ||
| 147 | #my $completed = delete $options{ cb }; | ||
| 148 | my $method = delete $options{ method }; | ||
| 149 | my $endpoint = delete $options{ api_endpoint }; | ||
| 150 | my $headers = delete $options{ headers } || {}; | ||
| 151 | $headers = { $self->get_headers, %$headers }; | ||
| 152 | my $body = delete $options{ _body }; | ||
| 153 | |||
| 154 | my $url; | ||
| 155 | if( ! $options{url} ) { | ||
| 156 | croak "Don't know the api_endpoint for the request" | ||
| 157 | unless $endpoint; | ||
| 158 | $url = URI->new( join( "/b2api/v1/", | ||
| 159 | $self->apiUrl, | ||
| 160 | $endpoint) | ||
| 161 | ); | ||
| 162 | } else { | ||
| 163 | $url = delete $options{ url }; | ||
| 164 | $url = URI->new( $url ) | ||
| 165 | if( ! ref $url ); | ||
| 166 | }; | ||
| 167 | for my $k ( keys %options ) { | ||
| 168 | my $v = $options{ $k }; | ||
| 169 | $url->query_param_append($k, $v); | ||
| 170 | }; | ||
| 171 | $self->log_message(1, sprintf "Sending %s request to %s", $method, $url); | ||
| 172 | |||
| 173 | my $res = deferred; | ||
| 174 | my $req; | ||
| 175 | $req = http_request $method => $url, | ||
| 176 | headers => $headers, | ||
| 177 | body => $body, | ||
| 178 | sub { | ||
| 179 | my( $data, $headers ) = @_; | ||
| 180 | undef $req; | ||
| 181 | $res->resolve($data, $headers); | ||
| 182 | #undef $res; # justin case | ||
| 183 | }, | ||
| 184 | ; | ||
| 185 | |||
| 186 | $res->promise | ||
| 187 | } | ||
| 188 | |||
| 189 | =head2 C<< ->json_request >> | ||
| 190 | |||
| 191 | my $res = $b2->json_request(...)->then(sub { | ||
| 192 | my( $ok, $message, @stuff ) = @_; | ||
| 193 | }); | ||
| 194 | |||
| 195 | Helper routine that expects a JSON formatted response | ||
| 196 | and returns the decoded JSON structure. | ||
| 197 | |||
| 198 | =cut | ||
| 199 | |||
| 200 | sub json_request { | ||
| 201 | my( $self, %options ) = @_; | ||
| 202 | $self->request( | ||
| 203 | %options | ||
| 204 | )->then(sub { | ||
| 205 | |||
| 206 | my( $body, $headers ) = @_; | ||
| 207 | |||
| 208 | my $d = deferred; | ||
| 209 | my @decoded = $self->decode_json_response($body, $headers); | ||
| 210 | my $result = $d->promise; | ||
| 211 | $d->resolve( @decoded ); | ||
| 212 | |||
| 213 | $result | ||
| 214 | }); | ||
| 215 | } | ||
| 216 | |||
| 217 | sub authorize_account { | ||
| 218 | my( $self, %options ) = @_; | ||
| 219 | $options{ accountId } | ||
| 220 | or croak "Need an accountId"; | ||
| 221 | $options{ applicationKey } | ||
| 222 | or croak "Need an applicationKey"; | ||
| 223 | my $auth= encode_base64( "$options{accountId}:$options{ applicationKey }" ); | ||
| 224 | |||
| 225 | my $url = $self->{api_base} . "b2_authorize_account"; | ||
| 226 | |||
| 227 | $self->json_request( | ||
| 228 | url => $url, | ||
| 229 | headers => { | ||
| 230 | "Authorization" => "Basic $auth" | ||
| 231 | }, | ||
| 232 | )->then( sub { | ||
| 233 | my( $ok, $msg, $cred ) = @_; | ||
| 234 | |||
| 235 | if( $ok ) { | ||
| 236 | $self->log_message(1, sprintf "Storing authorization token"); | ||
| 237 | |||
| 238 | $self->{credentials} = $cred; | ||
| 239 | }; | ||
| 240 | |||
| 241 | return ( $ok, $msg, $cred ); | ||
| 242 | }); | ||
| 243 | } | ||
| 244 | |||
| 245 | =head2 C<< $b2->create_bucket >> | ||
| 246 | |||
| 247 | $b2->create_bucket( | ||
| 248 | bucketName => 'my_files', | ||
| 249 | bucketType => 'allPrivate', | ||
| 250 | ); | ||
| 251 | |||
| 252 | Bucket names can consist of: letters, digits, "-", and "_". | ||
| 253 | |||
| 254 | L<https://www.backblaze.com/b2/docs/b2_create_bucket.html> | ||
| 255 | |||
| 256 | The C<bucketName> has to be B<globally> unique, so expect | ||
| 257 | this request to fail, a lot. | ||
| 258 | |||
| 259 | =cut | ||
| 260 | |||
| 261 | sub create_bucket { | ||
| 262 | my( $self, %options ) = @_; | ||
| 263 | |||
| 264 | croak "Need a bucket name" | ||
| 265 | unless defined $options{ bucketName }; | ||
| 266 | $options{ accountId } ||= $self->accountId; | ||
| 267 | $options{ bucketType } ||= 'allPrivate'; # let's be defensive here... | ||
| 268 | |||
| 269 | $self->json_request(api_endpoint => 'b2_create_bucket', | ||
| 270 | accountId => $options{ accountId }, | ||
| 271 | bucketName => $options{ bucketName }, | ||
| 272 | bucketType => $options{ bucketType }, | ||
| 273 | %options | ||
| 274 | ) | ||
| 275 | } | ||
| 276 | |||
| 277 | =head2 C<< $b2->delete_bucket >> | ||
| 278 | |||
| 279 | $b2->delete_bucket( | ||
| 280 | bucketId => ..., | ||
| 281 | ); | ||
| 282 | |||
| 283 | Bucket names can consist of: letters, digits, "-", and "_". | ||
| 284 | |||
| 285 | L<https://www.backblaze.com/b2/docs/b2_delete_bucket.html> | ||
| 286 | |||
| 287 | The bucket must be empty of all versions of all files. | ||
| 288 | |||
| 289 | =cut | ||
| 290 | |||
| 291 | sub delete_bucket { | ||
| 292 | my( $self, %options ) = @_; | ||
| 293 | |||
| 294 | croak "Need a bucketId" | ||
| 295 | unless defined $options{ bucketId }; | ||
| 296 | $options{ accountId } ||= $self->accountId; | ||
| 297 | |||
| 298 | my $res = AnyEvent->condvar; | ||
| 299 | $self->json_request(api_endpoint => 'b2_delete_bucket', | ||
| 300 | accountId => $options{ accountId }, | ||
| 301 | bucketId => $options{ bucketId }, | ||
| 302 | %options | ||
| 303 | ); | ||
| 304 | } | ||
| 305 | |||
| 306 | =head2 C<< $b2->list_buckets >> | ||
| 307 | |||
| 308 | $b2->list_buckets(); | ||
| 309 | |||
| 310 | L<https://www.backblaze.com/b2/docs/b2_list_buckets.html> | ||
| 311 | |||
| 312 | Returns the error status, the message and the payload. | ||
| 313 | |||
| 314 | =cut | ||
| 315 | |||
| 316 | sub list_buckets { | ||
| 317 | my( $self, %options ) = @_; | ||
| 318 | |||
| 319 | $options{ accountId } ||= $self->accountId; | ||
| 320 | |||
| 321 | $self->json_request(api_endpoint => 'b2_list_buckets', | ||
| 322 | accountId => $options{ accountId }, | ||
| 323 | %options | ||
| 324 | ) | ||
| 325 | } | ||
| 326 | |||
| 327 | =head2 C<< $b2->get_upload_url >> | ||
| 328 | |||
| 329 | my $upload_handle = $b2->get_upload_url(); | ||
| 330 | $b2->upload_file( file => $file, handle => $upload_handle ); | ||
| 331 | |||
| 332 | L<https://www.backblaze.com/b2/docs/b2_get_upload_url.html> | ||
| 333 | |||
| 334 | =cut | ||
| 335 | |||
| 336 | sub get_upload_url { | ||
| 337 | my( $self, %options ) = @_; | ||
| 338 | |||
| 339 | croak "Need a bucketId" | ||
| 340 | unless defined $options{ bucketId }; | ||
| 341 | |||
| 342 | $self->json_request(api_endpoint => 'b2_get_upload_url', | ||
| 343 | %options | ||
| 344 | ) | ||
| 345 | } | ||
| 346 | |||
| 347 | =head2 C<< $b2->upload_file >> | ||
| 348 | |||
| 349 | my $upload_handle = $b2->get_upload_url(); | ||
| 350 | $b2->upload_file( | ||
| 351 | file => $file, | ||
| 352 | handle => $upload_handle | ||
| 353 | ); | ||
| 354 | |||
| 355 | L<https://www.backblaze.com/b2/docs/b2_upload_file.html> | ||
| 356 | |||
| 357 | Note: This method loads the complete file to be uploaded | ||
| 358 | into memory. | ||
| 359 | |||
| 360 | Note: The Backblaze B2 API is vague about when you need | ||
| 361 | a new upload URL. | ||
| 362 | |||
| 363 | =cut | ||
| 364 | |||
| 365 | sub upload_file { | ||
| 366 | my( $self, %options ) = @_; | ||
| 367 | |||
| 368 | croak "Need an upload handle" | ||
| 369 | unless defined $options{ handle }; | ||
| 370 | my $handle = delete $options{ handle }; | ||
| 371 | |||
| 372 | croak "Need a source file name" | ||
| 373 | unless defined $options{ file }; | ||
| 374 | my $filename = delete $options{ file }; | ||
| 375 | |||
| 376 | my $target_filename = delete $options{ target_name }; | ||
| 377 | $target_filename ||= $filename; | ||
| 378 | $target_filename =~ s!\\!/!g; | ||
| 379 | $target_filename = encode('UTF-8', $target_filename ); | ||
| 380 | $target_filename =~ s!([^\x21-\x7d])!sprintf "%%%02x", ord $1!ge; | ||
| 381 | |||
| 382 | my $mime_type = delete $options{ mime_type } || 'b2/x-auto'; | ||
| 383 | |||
| 384 | if( not defined $options{ content }) { | ||
| 385 | open my $fh, '<', $filename | ||
| 386 | or croak "Couldn't open '$filename': $!"; | ||
| 387 | binmode $fh, ':raw'; | ||
| 388 | $options{ content } = do { local $/; <$fh> }; # sluuuuurp | ||
| 389 | $options{ mtime } = ((stat($fh))[9]) * 1000; | ||
| 390 | }; | ||
| 391 | |||
| 392 | my $payload = delete $options{ content }; | ||
| 393 | if( not $options{ sha1 }) { | ||
| 394 | my $sha1 = Digest::SHA1->new; | ||
| 395 | $sha1->add( $payload ); | ||
| 396 | $options{ sha1 } = $sha1->hexdigest; | ||
| 397 | }; | ||
| 398 | my $digest = delete $options{ sha1 }; | ||
| 399 | my $size = length($payload); | ||
| 400 | my $mtime = delete $options{ mtime }; | ||
| 401 | |||
| 402 | $self->json_request( | ||
| 403 | url => $handle->{uploadUrl}, | ||
| 404 | method => 'POST', | ||
| 405 | _body => $payload, | ||
| 406 | headers => { | ||
| 407 | 'Content-Type' => $mime_type, | ||
| 408 | 'Content-Length' => $size, | ||
| 409 | 'X-Bz-Content-Sha1' => $digest, | ||
| 410 | 'X-Bz-File-Name' => $target_filename, | ||
| 411 | 'Authorization' => $handle->{authorizationToken}, | ||
| 412 | }, | ||
| 413 | %options | ||
| 414 | ); | ||
| 415 | } | ||
| 416 | |||
| 417 | =head2 C<< $b2->list_file_names >> | ||
| 418 | |||
| 419 | my $startFileName; | ||
| 420 | my $list = $b2->list_file_names( | ||
| 421 | startFileName => $startFileName, | ||
| 422 | maxFileCount => 1000, # maximum per round | ||
| 423 | bucketId => ..., | ||
| 424 | |||
| 425 | ); | ||
| 426 | |||
| 427 | L<https://www.backblaze.com/b2/docs/b2_list_file_names.html> | ||
| 428 | |||
| 429 | =cut | ||
| 430 | |||
| 431 | sub list_file_names { | ||
| 432 | my( $self, %options ) = @_; | ||
| 433 | |||
| 434 | croak "Need a bucket id" | ||
| 435 | unless defined $options{ bucketId }; | ||
| 436 | |||
| 437 | $self->json_request( | ||
| 438 | api_endpoint => 'b2_list_file_names', | ||
| 439 | %options | ||
| 440 | ); | ||
| 441 | } | ||
| 442 | |||
| 443 | =head2 C<< $b2->list_all_file_names >> | ||
| 444 | |||
| 445 | my $list = $b2->list_all_file_names( | ||
| 446 | startFileName => $startFileName, | ||
| 447 | maxFileCount => 1000, # maximum per round | ||
| 448 | bucketId => ..., | ||
| 449 | |||
| 450 | ); | ||
| 451 | |||
| 452 | Retrieves all filenames in a bucket | ||
| 453 | |||
| 454 | =cut | ||
| 455 | |||
| 456 | sub list_all_file_names { | ||
| 457 | my( $self, %options ) = @_; | ||
| 458 | |||
| 459 | croak "Need a bucket id" | ||
| 460 | unless defined $options{ bucketId }; | ||
| 461 | |||
| 462 | my @results; | ||
| 463 | |||
| 464 | my $handle_response; $handle_response = sub { | ||
| 465 | my( $ok, $msg, $results ) = @_; | ||
| 466 | |||
| 467 | $self->log_message(1, sprintf "Got filenames starting from '%s' to '%s'", | ||
| 468 | $options{startFileName} || '', | ||
| 469 | $results->{nextFileName} || ''); | ||
| 470 | #use Data::Dumper; | ||
| 471 | #warn Dumper $results; | ||
| 472 | |||
| 473 | push @results, @{ $results->{files} }; | ||
| 474 | |||
| 475 | if( $results->{ endFileName }) { | ||
| 476 | $options{ startFileName } = $results->{nextFileName}; | ||
| 477 | |||
| 478 | $self->log_message(1, sprintf "Requesting filenames starting from '%s'", | ||
| 479 | $options{startFileName} || ''); | ||
| 480 | # We recurse deeper, but AnyEvent should handle the stack for us | ||
| 481 | return | ||
| 482 | $self->list_file_names( %options ) | ||
| 483 | ->then( $handle_response ); | ||
| 484 | } else { | ||
| 485 | # We've collected all items | ||
| 486 | my $res = deferred; | ||
| 487 | $res->resolve(1, "", @results); | ||
| 488 | $res->promise | ||
| 489 | } | ||
| 490 | }; | ||
| 491 | |||
| 492 | $self->log_message(1, sprintf "Requesting filenames starting from '%s'", $options{startFileName} || ''); | ||
| 493 | $self->list_file_names( %options ) | ||
| 494 | ->then( $handle_response ); | ||
| 495 | } | ||
| 496 | |||
| 497 | |||
| 498 | =head2 C<< $b2->download_file_by_name >> | ||
| 499 | |||
| 500 | my $content = $b2->download_file_by_name( | ||
| 501 | bucketName => $my_bucket_name, | ||
| 502 | fileName => $my_file_name, | ||
| 503 | ); | ||
| 504 | |||
| 505 | L<https://www.backblaze.com/b2/docs/b2_download_file_by_name.html> | ||
| 506 | |||
| 507 | =cut | ||
| 508 | |||
| 509 | sub download_file_by_name { | ||
| 510 | my( $self, %options ) = @_; | ||
| 511 | |||
| 512 | croak "Need a bucket name" | ||
| 513 | unless defined $options{ bucketName }; | ||
| 514 | croak "Need a file name" | ||
| 515 | unless defined $options{ fileName }; | ||
| 516 | my $url = join '/', | ||
| 517 | $self->{credentials}->{downloadUrl}, | ||
| 518 | 'file', | ||
| 519 | delete $options{ bucketName }, | ||
| 520 | delete $options{ fileName } | ||
| 521 | ; | ||
| 522 | $self->log_message(1, sprintf "Fetching %s", $url ); | ||
| 523 | |||
| 524 | $self->request( | ||
| 525 | url => $url, | ||
| 526 | %options | ||
| 527 | )->then(sub { | ||
| 528 | my( $body, $hdr ) = @_; | ||
| 529 | $self->log_message(2, sprintf "Fetching %s, received %d bytes", $url, length $body ); | ||
| 530 | my $ok = $hdr->{Status} =~ /^2\d\d/; | ||
| 531 | return( $ok, $hdr->{Reason}, $body ); | ||
| 532 | }) | ||
| 533 | } | ||
| 534 | |||
| 535 | =head2 C<< $b2->get_download_authorization >> | ||
| 536 | |||
| 537 | my $content = $b2->get_download_authorization( | ||
| 538 | bucketId => $my_bucket_id, | ||
| 539 | fileNamePrefix => $my_file_name, | ||
| 540 | validDurationInSeconds => 300, # you have five minutes to start the download | ||
| 541 | ); | ||
| 542 | |||
| 543 | L<https://www.backblaze.com/b2/docs/b2_get_download_authorization.html> | ||
| 544 | |||
| 545 | =cut | ||
| 546 | |||
| 547 | sub get_download_authorization { | ||
| 548 | my( $self, %options ) = @_; | ||
| 549 | |||
| 550 | croak "Need a bucket id" | ||
| 551 | unless defined $options{ bucketId }; | ||
| 552 | croak "Need a file name prefix" | ||
| 553 | unless defined $options{ fileNamePrefix }; | ||
| 554 | croak "Need a duration for the token" | ||
| 555 | unless defined $options{ validDurationInSeconds }; | ||
| 556 | |||
| 557 | $self->json_request( | ||
| 558 | api_endpoint => 'b2_get_download_authorization', | ||
| 559 | %options | ||
| 560 | ); | ||
| 561 | } | ||
| 562 | |||
| 563 | |||
| 564 | 1; |