Backblaze-B2

 view release on metacpan or  search on metacpan

lib/Backblaze/B2/v1/AnyEvent.pm  view on Meta::CPAN

package Backblaze::B2::v1::AnyEvent;
use strict;
use JSON::XS;
use MIME::Base64;
use URI::QueryParam;
use Carp qw(croak);

use Promises
    backend => ['AnyEvent'], 'deferred';
use AnyEvent;
use AnyEvent::HTTP;
use URI;
use URI::Escape;
use Digest::SHA1;
use File::Basename;
use Encode;
use Data::Dumper;

use vars qw(@CARP_NOT $VERSION);
$VERSION = '0.02';
@CARP_NOT = qw(Backblaze::B2::v1::Synchronous);

sub isAsync { 1 }
sub api { $_[0] }
sub asyncApi { $_[0] }

sub new {
    my( $class, %options ) = @_;

    require Backblaze::B2;
    
    $options{ api_base } //= $Backblaze::B2::v1::API_BASE
                           = $Backblaze::B2::v1::API_BASE;

    croak "Need an API base"
        unless $options{ api_base };
    
    bless \%options => $class;
}

sub log_message {
    my( $self ) = shift;
    if( $self->{log_message}) {
        goto &{ $self->{log_message}};
    };
}

sub read_credentials {
    my( $self, $file ) = @_;
    
    if( ! defined $file) {
        require File::HomeDir;
        $file = File::HomeDir->my_home . "/credentials.b2";
        $self->log_message(0, "Using default credentials file '$file'");
    };
    
    $self->log_message(1, "Reading credentials from '$file'");
    
    open my $fh, '<', $file
        or croak "Couldn't read credentials from '$file': $!";
    binmode $fh;
    local $/;
    my $json = <$fh>;
    my $cred = decode_json( $json );
    
    $self->{credentials} = $cred;
    
    $cred
};

sub decode_json_response {
    my($self, $body,$hdr) = @_;
    
    $self->log_message(1, sprintf "HTTP Response status %d", $hdr->{Status});

    my @result;
    if( !$body) {
        $self->log_message(4, sprintf "No response body received");
        @result = (0, "No response body received", $hdr);
    } else {
        
        my $b = eval { decode_json( $body ); };
        if( my $err = $@ ) {
            $self->log_message(4, sprintf "Error decoding JSON response body: %s", $err);
            @result = (0, sprintf("Error decoding JSON response body: %s", $err), $hdr);
        } elsif( $hdr->{Status} =~ /^[45]\d\d$/ ) {
            my $reason = $b->{message} || $hdr->{Reason};
            my $status = $b->{status}  || $hdr->{Status};
            $self->log_message(4, sprintf "HTTP error status: %s: %s", $status, $reason);
            @result = ( 0, sprintf(sprintf "HTTP error status: %s: %s", $status, $reason));
        } else {
            @result = (1, "", $b);
        };
    };
    
    @result
}

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 1.013 second using v1.00-cache-1.14-grep-28634ff-cpan-207214f8fbd )