blib/lib/Backblaze/B2V4.pm

filter: Statementstmt 78.9% 94 / 119 Branchbran 50.0% 19 / 38 Conditioncond 42.8% 6 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 95.0% 19 / 20 Podpod 0.0% 0 / 3 totaltotal 67.9% 138 / 203 CC 26 SCAR 24.2
CC
26
Cov
70%
send_request
28.9
latest_error
7.7
b2_get_file_info
5.0
CRAP 11.2
↑ Summary Build »
1 package Backblaze::B2V4;
2 # API client library for V2 of the API to Backblaze B2 object storage
3 # Allows for creating/deleting buckets, listing files in buckets, and uploading/downloading files
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 our $VERSION = "0.03";
9  
10 1 ▶use v5.38; # or higher
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Cpanel::JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Digest::SHA qw(sha1_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 1 ▶use Types::Common -all;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use Marlin::Util -all;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 use Marlin
21 1 'application_key_id' => { is => 'ro', isa => 'NonEmptyStr' },
22 'application_key' => { is => 'ro', isa => 'NonEmptyStr' },
23 'current_status_is_not_ok' => { is => 'rw', isa => 'Bool', default => 0 },
24 'login_error' => { is => 'rw', isa => 'Bool', default => 0 },
25 'errors' => { is => 'rw', isa => 'ArrayRef', default => [] },
26 'api_info' => { is => 'rw', isa => 'HashRef', builder => 'build_api_info' },
27 'bucket_info' => { is => 'rw', isa => 'HashRef', default => {} },
28 'file_info' => { is => 'rw', isa => 'HashRef', default => {} },
29 1 ▶ ;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 # builder method to create api_info hashref attribute
32 ▶sub build_api_info ($self) {
Subroutine build_api_info: called CC=3 SCAR=13.3
Pod undocumented
33 1 my $response = $self->send_request(
34 url => 'b2_authorize_account',
35 authorization => 'Basic ' . encode_base64($self->application_key_id . ':' . $self->application_key, ''),
36 );
37  
38 1 ▶ if (!$response) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response) 0 1 1
39 0 $self->login_error(1);
40 0 return {};
41 }
42  
43 return {
44 'account_id' => $response->{accountId},
45 'api_url' => $response->{apiInfo}->{storageApi}->{apiUrl} . '/b2api/v4/',
46 'account_authorization_token' => $response->{authorizationToken},
47 'download_url' => $response->{apiInfo}->{storageApi}->{downloadUrl},
48 1 ▶ 'recommended_part_size' => $response->{apiInfo}->{storageApi}->{recommendedPartSize} || 104857600
Condition50%1/2
$response->{'apiInfo'}{'storageApi'}{'recommendedPartSize'} || 104857600
l!l
10
MC/DC0%0/1
$response->{'apiInfo'}{'storageApi'}{'recommendedPartSize'} || 104857600
$response->{'apiInfo'}{'storageApi'}{'recommendedPartSize'}
Truth table50%1/2
A
A= $response->{'apiInfo'}{'storageApi'}{'recommendedPartSize'}
Aresult
11
00
49 };
50 }
51  
52 # generic method to handle communication to B2
53 1 signature_for send_request => (
54 method => true,
55 named => [
56 url => NonEmptyStr,
57 authorization => Str, { optional => true },
58 headers => HashRef, { optional => true, default => {} },
59 post_params => HashRef, { optional => true },
60 file_contents => Value, { optional => true },
61 ],
62 returns => Bool|HashRef,
63 );
64  
65 ▶sub send_request ($self, $args) {
Subroutine send_request: called CC=14 SCAR=33.6
66 4 my $headers = $args->headers;
67 4 ▶ $headers->{'Authorization'} = $args->authorization || $self->api_info->{account_authorization_token};
Condition66%2/3
$args->authorization || $self->api_info->{'account_authorization_token'}
l!l&&r!l&&!r
130
MC/DC0%0/2
$args->authorization || $self->api_info->{'account_authorization_token'}
$args->authorization $self->api_info->{'account_authorization_token'}
Truth table66%2/3
A || B
A= $args->authorizationB= $self->api_info->{'account_authorization_token'}
ABresult
1X1
011
000
68  
69 4 my $api_url = $args->url;
70 4 ▶ if ($args->url eq 'b2_authorize_account') {
Branch: 2 branches
BranchTrueFalseTotal
if ($args->url eq 'b2_authorize_account') { } 1 3 4
elsif (not $args->url =~ /^https/u) { } 1 2 3
71 1 $api_url = 'https://api.backblazeb2.com/b2api/v4/b2_authorize_account';
72 } elsif ($args->url !~ /^https/) {
73 1 $api_url = $self->api_info->{api_url} . $args->url;
74 }
75
76 # short-circuit if we had difficulty logging in previously
77 4 ▶ if ($self->login_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->login_error) 0 4 4
78 # track the error / set current state
79 0 return $self->error_tracker(
80 'error_message' => "Problem logging into Backblaze. Please check the 'errors' array in this object.",
81 'url' => $args->url,
82 );
83 }
84  
85 4 my $b2_response = {};
86 4 my $response;
87  
88 # are we uploading a file?
89 4 ▶ if ($args->url =~ /b2_upload_file|b2_upload_part/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args->url =~ /b2_upload_file|b2_upload_part/u) { } 0 4 4
elsif ($args->post_params) { } 0 4 4
90 # now upload the file
91 0 eval {
92 0 $response = HTTP::Tiny->new->post($api_url, {
93 'headers' => $headers,
94 'content' => $args->file_contents
95 });
96 0 $b2_response = decode_json( $response->{content} );
97 };
98  
99 # if not uploading and they sent POST params, we are doing a POST
100 } elsif ($args->post_params) {
101 0 eval {
102 0 $response = HTTP::Tiny->new->post($api_url, {
103 'headers' => $headers,
104 'content' => encode_json($args->post_params)
105 });
106 0 $b2_response = decode_json( $response->{content} );
107 };
108  
109 # otherwise, we are attempting a GET
110 } else {
111 4 eval {
112 4 $response = HTTP::Tiny->new->get($api_url, {
113 'headers' => $headers,
114 });
115  
116 # did we download a file?
117 4 ▶ if ($response->{headers}->{'x-bz-file-name'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($response->{'headers'}{'x-bz-file-name'}) { } 2 2 4
elsif ($response->{'status'} == 200) { } 2 0 2
118 # grab those needed headers
119 2 foreach my $header ('content-length', 'content-type', 'x-bz-file-id', 'x-bz-file-name', 'x-bz-content-sha1') {
120 10 $b2_response->{$header} = $response->{headers}->{$header};
121 }
122  
123 # and the file itself
124 2 $b2_response->{file_contents} = $response->{content};
125  
126 } elsif ($response->{status} == 200) { # regular JSON, decode results
127 2 $b2_response = decode_json( $response->{content} );
128 }
129 };
130 }
131
132 # there is a problem if there is a problem
133 4 ▶ if ($@ || $response->{status} != 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or $response->{"status"} != 200) 0 4 4
Condition33%1/3
$@ or $response->{"status"} != 200
l!l&&r!l&&!r
004
MC/DC0%0/2
$@ or $response->{"status"} != 200
$@ $response->{"status"} != 200
Truth table33%1/3
A or B
A= $@B= $response->{"status"} != 200
ABresult
1X1
011
000
134 0 my $error_message;
135 0 ▶ if ($b2_response->{message}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($b2_response->{'message'}) { } 0 0 0
elsif ($@) { } 0 0 0
136 0 $error_message = 'API Message: ' . $b2_response->{message};
137 } elsif ($@) {
138 0 $error_message = 'Error: ' . $@;
139 } else {
140 0 $error_message = 'Error: ' . $response->{reason};
141 }
142  
143 # track the error / set current state
144 return $self->error_tracker(
145 0 'error_message' => $error_message . ' (' . $response->{status} . ')',
146 'url' => $args->url,
147 );
148 }
149
150 4 $self->current_status_is_not_ok(0);
151 4 return $b2_response;
152 }
153  
154 # indicate if everything is fine
155 ▶sub current_status_is_ok ($self) {
Subroutine current_status_is_ok: not called CC=1 SCAR=6.9
Pod undocumented
156 0 return !$self->current_status_is_not_ok;
157 }
158  
159 # for tracking errors into $self->{errrors}[];
160 1 signature_for error_tracker => (
161 method => true,
162 named => [
163 error_message => Str,
164 url => Str,
165 ],
166 returns => Bool,
167 );
168  
169 sub error_tracker ($self, $args) {
170 push(@{ $self->errors }, {
171 'error_message' => $args->error_message,
172 'url' => $args->url,
173 });
174  
175 $self->current_status_is_not_ok(1);
176
177 return 0;
178 }
179  
180 # please tell me the lastest error message
181 ▶sub latest_error ($self) {
Subroutine latest_error: called CC=4 SCAR=20.4
Pod undocumented
182 5 my $latest_error = $self->errors->[-1];
183 5 ▶ if (!$latest_error || !$latest_error->{error_message}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($latest_error and $latest_error->{"error_message"}) 5 0 5
Condition33%1/3
$latest_error and $latest_error->{"error_message"}
!ll&&!rl&&r
500
MC/DC0%0/2
$latest_error and $latest_error->{"error_message"}
$latest_error $latest_error->{"error_message"}
Truth table33%1/3
A and B
A= $latest_errorB= $latest_error->{"error_message"}
ABresult
0X0
100
111
184 5 return 'No error message found';
185 }
186
187 0 my $error_message = $latest_error->{error_message};
188 0 ▶ $error_message .= ' / ' . $latest_error->{url} if $latest_error->{url};
Branch: 1 branch
BranchTrueFalseTotal
if $latest_error->{"url"} 0 0 0
189  
190 0 return $error_message;
191 }
192  
193 # method to save downloaded files into a target location
194 # only call after successfully calling b2_download_file_by_id() or b2_download_file_by_name()
195 1 signature_for save_downloaded_file => (
196 method => true,
197 named => [
198 save_to_location => NonEmptyStr,
199 response => HashRef,
200 ],
201 returns => Bool,
202 );
203  
204 sub save_downloaded_file ($self, $args) {
205 # error out if that location don't exist
206 if (!(-d $args->save_to_location)) {
207 return $self->error_tracker(
208 'error_message' => "Can not auto-save file without a valid location. " . $args->save_to_location,
209 'url' => 'save_downloaded_file',
210 );
211 }
212  
213 # make sure they actually downloaded a file
214 if ( !$args->response->{'x-bz-file-name'} || !length($args->response->{file_contents}) ) {
215 return $self->error_tracker(
216 'error_message' => "Can not auto-save without first downloading a file.",
217 'url' => 'save_downloaded_file',
218 );
219 }
220  
221 # still here? do the save
222  
223 # add the filename
224 my $save_to_location = $args->save_to_location . '/' . $args->response->{'x-bz-file-name'};
225  
226 # i really love Path::Tiny
227 path($save_to_location)->spew_raw( $args->response->{file_contents} );
228  
229 # return OK
230 return 1;
231 }
232  
233 ## Start actual public methods ##
234  
235 # method to download a file by ID; probably most commonly used
236 1 signature_for b2_download_file_by_id => (
237 method => true,
238 named => [
239 file_id => NonEmptyStr,
240 save_to_location => Str, { optional => true },
241 ],
242 returns => Bool|HashRef,
243 );
244  
245 ▶sub b2_download_file_by_id ($self, $args) {
Subroutine b2_download_file_by_id: called CC=3 SCAR=12.7
246 my $response = $self->send_request(
247 1 'url' => $self->api_info->{download_url} . '/b2api/v4/b2_download_file_by_id' . '?fileId=' . $args->file_id,
248 );
249  
250 1 ▶ if ($self->current_status_is_not_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->current_status_is_not_ok) 0 1 1
251 0 return 0;
252 }
253  
254 # if they provided a save-to location (a directory) and the file was found, let's save it out
255 1 ▶ if ($args->save_to_location) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->save_to_location) 0 1 1
256 0 $self->save_downloaded_file(
257 save_to_location => $args->save_to_location,
258 response => $response
259 );
260 }
261  
262 # return file contents
263 1 return $response;
264 }
265  
266 # method to download a file via the bucket name + file name
267 1 signature_for b2_download_file_by_name => (
268 method => true,
269 named => [
270 bucket_name => NonEmptyStr,
271 file_name => NonEmptyStr,
272 save_to_location => Str, { optional => true },
273 ],
274 returns => Bool|HashRef,
275 );
276  
277 ▶sub b2_download_file_by_name ($self, $args) {
Subroutine b2_download_file_by_name: called CC=3 SCAR=12.7
278 # send the request, as a GET
279 my $response = $self->send_request(
280 1 'url' => $self->api_info->{download_url} . '/file/' . uri_escape($args->bucket_name) . '/' . uri_escape($args->file_name),
281 );
282  
283 # if the file was found, you will have the relevant headers in $response
284 # as well as the file's contents in $response->{file_contents}
285 1 ▶ if ($self->current_status_is_not_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->current_status_is_not_ok) 0 1 1
286 0 return 0;
287 }
288  
289 # if they provided a save-to location (a directory) and the file was found, let's save it out
290 1 ▶ if ($args->save_to_location) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->save_to_location) 0 1 1
291 0 $self->save_downloaded_file(
292 save_to_location => $args->save_to_location,
293 response => $response
294 );
295 }
296  
297 # return file contents
298 1 return $response;
299 }
300  
301 # method to upload a file into Backblaze B2
302 1 signature_for b2_upload_file => (
303 method => true,
304 named => [
305 new_file_name => NonEmptyStr, { optional => true },
306 bucket_name => NonEmptyStr,
307 content_type => Str, { optional => true, default => 'b2/x-auto' },
308 file_location => Str, { optional => true },
309 file_contents => Value, { optional => true },
310 ],
311 returns => Bool|Str,
312 );
313  
314 sub b2_upload_file ($self, $args) {
315 # send the file contents?
316 my $file_contents = $args->file_contents;
317 my $new_file_name = $args->new_file_name;
318
319 # did they provide a file location or path?
320 if (!$file_contents && $args->file_location && -e $args->file_location) {
321 $file_contents = path( $args->file_location )->slurp_raw;
322 # if they didn't provide a file-name, use the one on this file
323 if (!$new_file_name) {
324 $new_file_name = path( $args->file_location )->basename;
325 }
326 }
327  
328 if (!$file_contents) {
329 return $self->error_tracker(
330 'error_message' => qq{You must provide either a valid 'file_location' or 'file_contents' arg for b2_upload_file()},
331 'url' => 'b2_upload_file',
332 );
333 }
334  
335 if (!$new_file_name || !$args->bucket_name) {
336 return $self->error_tracker(
337 'error_message' => qq{You must provide 'bucket_name' and 'new_file_name' args for b2_upload_file().},
338 'url' => 'b2_upload_file',
339 );
340 }
341  
342 my $content_type = $args->content_type || 'b2/x-auto';
343 my $upload_info = $self->b2_get_upload_info( bucket_name => $args->bucket_name );
344 if (!$upload_info) {
345 return 0;
346 }
347  
348 # send the special request
349 my $response => $self->send_request(
350 'url' => $upload_info->{upload_url},
351 'authorization' => $upload_info->{authorization_token},
352 'file_contents' => $file_contents,
353 'headers' => {
354 'X-Bz-File-Name' => uri_escape( $new_file_name ),
355 'X-Bz-Content-Sha1' => sha1_hex( $file_contents ),
356 'Content-Type' => $content_type,
357 },
358 );
359
360 return $self->current_status_is_not_ok ? 0 : $response->{fileId};
361 }
362  
363 # method to get the information needed to upload into a specific B2 bucket
364 1 signature_for b2_get_upload_info => (
365 method => true,
366 named => [
367 bucket_name => NonEmptyStr,
368 ],
369 returns => HashRef|Bool,
370 );
371  
372 sub b2_get_upload_info ($self, $args) {
373 my $response = $self->send_request(
374 'url' => 'b2_get_upload_url',
375 'post_params' => {
376 'bucketId' => $self->b2_get_bucket_id(
377 'bucket_name' => $args->bucket_name,
378 ),
379 },
380 );
381
382 if (!$response) {
383 return 0;
384 }
385
386 return {
387 'upload_url' => $response->{uploadUrl},
388 'authorization_token' => $response->{authorizationToken},
389 };
390 }
391  
392 1 signature_for b2_get_bucket_id => (
393 method => true,
394 named => [
395 bucket_name => NonEmptyStr,
396 auto_create_bucket => Bool, { optional => true, default => true },
397 ],
398 returns => Str|Bool,
399 );
400  
401 sub b2_get_bucket_id ($self, $args) {
402 my $bucket_name = $args->bucket_name;
403
404 return $self->bucket_info->{$bucket_name}->{bucket_id}
405 if $self->bucket_info->{$bucket_name} && ref($self->bucket_info->{$bucket_name}) eq 'HASH';
406  
407 my $ok = $self->b2_list_buckets(
408 bucket_name => $bucket_name,
409 auto_create_bucket => $args->auto_create_bucket,
410 );
411
412 if ($ok) {
413 return $self->bucket_info->{$bucket_name}->{bucket_id};
414 }
415
416 return 0;
417 }
418  
419 # method to load information on one bucket or all buckets
420 1 signature_for b2_list_buckets => (
421 method => true,
422 named => [
423 bucket_name => Str, { optional => true, default => '' },
424 auto_create_bucket => Bool, { optional => true, default => 0 },
425 ],
426 returns => Bool,
427 );
428  
429 sub b2_list_buckets ($self, $args) {
430 # no need if we already have it
431 return 1 if $self->bucket_info->{$args->bucket_name}->{bucket_id};
432  
433 my $post_params = {
434 'accountId' => $self->api_info->{account_id}
435 };
436
437 if ($args->bucket_name) {
438 $post_params->{bucketName} = $args->bucket_name;
439 }
440  
441 # send the request
442 my $response = $self->send_request(
443 'url' => 'b2_list_buckets',
444 'post_params' => $post_params,
445 );
446  
447 if ($self->current_status_is_not_ok) {
448 return 0;
449 }
450  
451 # if we succeeded, load in all the found buckets to $self->{buckets}
452 # that will be a hash of info, keyed by name
453  
454 my $bucket_name;
455 foreach my $bucket_info (@{ $response->{buckets} }) {
456 $bucket_name = $bucket_info->{bucketName};
457 $self->bucket_info->{$bucket_name} = {
458 'bucket_id' => $bucket_info->{bucketId},
459 'bucket_type' => $bucket_info->{bucketType},
460 };
461 }
462  
463 # if that bucket was not found, maybe they want to go ahead and create it?
464 $bucket_name = $args->bucket_name;
465 if ($bucket_name && !$self->bucket_info->{$bucket_name}->{bucket_id} && $args->auto_create_bucket) {
466 $self->b2_bucket_maker(
467 bucket_name => $bucket_name
468 );
469 if ($self->current_status_is_not_ok) {
470 return 0;
471 }
472 # this will call back to me and get the info
473 }
474
475 return 1;
476 }
477  
478 # method to retrieve file names / info from a bucket
479 # this client library is bucket-name-centric, so it looks for the bucket name as a arg
480 # if there are more than 1000 files, then call this repeatedly
481 1 signature_for b2_list_file_names => (
482 method => true,
483 named => [
484 bucket_name => Str,
485 prefix => Str, { optional => true, default => ''},
486 delimiter => Str, { optional => true, default => ''},
487 start_file_name => Str, { optional => true, default => ''},
488 ],
489 returns => Bool|ArrayRef,
490 );
491  
492 sub b2_list_file_names ($self, $args) {
493 my $bucket_name = $args->bucket_name;
494  
495 my $post_params = {
496 'bucketId' => $self->b2_get_bucket_id( 'bucket_name' => $bucket_name ),
497 };
498
499 foreach my $key ('prefix', 'delimiter') {
500 if ($args->$key) {
501 $post_params->{$key} = $args->$key;
502 }
503 }
504  
505 if ($args->start_file_name) {
506 $post_params->{startFileName} = $args->start_file_name;
507 }
508  
509 my $response = $self->send_request(
510 'url' => 'b2_list_file_names',
511 'post_params' => $post_params,
512 );
513  
514 # if we succeeded, read in the files
515 if ($self->current_status_is_not_ok) {
516 return 0;
517 }
518
519 $self->bucket_info->{$bucket_name}->{next_file_name} = $response->{nextFileName};
520  
521 # add to our possibly-started array of file info for this bucket
522 push(
523 @{ $self->{buckets}{$bucket_name}{files} },
524 @{ $response->{files} }
525 );
526  
527 # kindly return the request results as a reference (arrayref)
528 return $response->{files};
529 }
530  
531 # method to get info for a specific file
532 1 signature_for b2_get_file_info => (
533 method => true,
534 named => [
535 file_id => Str,
536 ],
537 returns => Bool|HashRef,
538 );
539  
540 ▶sub b2_get_file_info ($self, $args) {
Subroutine b2_get_file_info: called CC=4 SCAR=16.1
541 1 my $file_id = $args->file_id;
542
543 1 ▶ if ($self->file_info->{$file_id} && ref($self->file_info->{$file_id}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->file_info->{$file_id} and ref $self->file_info->{$file_id} eq "HASH") 0 1 1
Condition33%1/3
$self->file_info->{$file_id} and ref $self->file_info->{$file_id} eq "HASH"
!ll&&!rl&&r
100
MC/DC0%0/2
$self->file_info->{$file_id} and ref $self->file_info->{$file_id} eq "HASH"
$self->file_info->{$file_id} ref $self->file_info->{$file_id} eq "HASH"
Truth table33%1/3
A and B
A= $self->file_info->{$file_id}B= ref $self->file_info->{$file_id} eq "HASH"
ABresult
0X0
100
111
544 0 return $self->file_info->{$file_id};
545 }
546  
547 # retrieve the file information
548 1 my $response = $self->send_request(
549 'url' => 'b2_get_file_info?fileId=' . $file_id,
550 );
551
552 1 ▶ if ($self->current_status_is_not_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->current_status_is_not_ok) 0 1 1
553 0 return 0;
554 }
555  
556 # i am not going to waste the CPU cycles de-camelizing these sub-keys
557 1 $self->file_info->{$file_id} = $response;
558  
559 1 return $response;
560 }
561  
562 # method to create a bucket
563 1 signature_for b2_bucket_maker => (
564 method => true,
565 named => [
566 bucket_name => NonEmptyStr,
567 disable_encryption => Bool, { optional => true, default => 0},
568 ],
569 returns => Bool,
570 );
571  
572 sub b2_bucket_maker ($self, $args) {
573 # prepare the basics for our request
574 my $post_params = {
575 'accountId' => $self->api_info->{account_id},
576 'bucketName' => $args->bucket_name,
577 'bucketType' => 'allPrivate',
578 };
579  
580 # unless instructed otherwise, we should encrypt the files in this bucket
581 unless ($args->disable_encryption) {
582 $post_params->{defaultServerSideEncryption} = {
583 'mode' => 'SSE-B2',
584 'algorithm' => 'AES256',
585 };
586 }
587  
588 # create the bucket...
589 my $response = $self->send_request(
590 'url' => 'b2_create_bucket',
591 'post_params' => $post_params,
592 );
593  
594 if ($self->current_status_is_not_ok) {
595 return 0;
596 }
597  
598 # otherwise successful, stash our new bucket into $self->{buckets}
599 $self->bucket_info->{$args->bucket_name} = {
600 'bucket_id' => $response->{bucketId},
601 'bucket_type' => 'allPrivate',
602 };
603  
604 return 1;
605 }
606  
607 # method to delete a bucket -- please don't use ;)
608 1 signature_for b2_delete_bucket => (
609 method => true,
610 named => [
611 bucket_name => NonEmptyStr,
612 ],
613 returns => Bool,
614 );
615  
616 sub b2_delete_bucket ($self, $args) {
617 my $bucket_id = $self->b2_get_bucket_id($args->bucket_name);
618 if (!$bucket_id) {
619 return $self->error_tracker(
620 'error_message' => 'Can not delete ' . $args->bucket_name . ' because bucket not found.',
621 );
622 }
623  
624 # send the request
625 $self->send_request(
626 'url' => 'b2_delete_bucket',
627 'post_params' => {
628 'accountId' => $self->api_info->account_id,
629 'bucketId' => $bucket_id,
630 },
631 );
632
633 return $self->current_status_is_not_ok ? 0 : 1;
634 }
635  
636 # method to delete a stored file object. B2 thinks of these as 'versions,'
637 # but if you use unique names, one version = one file
638 1 signature_for b2_delete_file_version => (
639 method => true,
640 named => [
641 file_name => NonEmptyStr,
642 file_id => NonEmptyStr,
643 ],
644 returns => Bool,
645 );
646  
647 sub b2_delete_file_version ($self, $args) {
648 # send the request
649 $self->send_request(
650 'url' => 'b2_delete_file_version',
651 'post_params' => {
652 'fileName' => $args->file_name,
653 'fileId' => $args->file_id,
654 },
655 );
656  
657 return $self->current_status_is_not_ok ? 0 : 1;
658 }
659  
660 # method to upload a large file (>100MB)
661 1 signature_for b2_upload_large_file => (
662 method => true,
663 named => [
664 new_file_name => NonEmptyStr,
665 bucket_name => NonEmptyStr,
666 file_location => NonEmptyStr,
667 content_type => NonEmptyStr, { optional => true, default => 'b2/x-auto' },
668 ],
669 returns => Bool|Str,
670 );
671  
672 sub b2_upload_large_file ($self, $args) {
673 # did they provide a file location or path?
674 if ($args->file_location && -e $args->file_location) {
675 # if they didn't provide a file-name, use the one on this file
676 $args->new_file_name = path( $args->file_location )->basename;
677 } else {
678 return $self->error_tracker(
679 'error_message' => "You must provide a valid 'file_location' arg for b2_upload_large_file().",
680 );
681 }
682  
683 # must be 100MB or bigger
684 my $stat = path($args->file_location)->stat;
685 if ($stat->size < $self->api_info->{recommended_part_size} ) {
686 return $self->error_tracker(
687 'error_message' => 'Please use b2_upload_large_file() for files larger than ' . $self->api_info->{recommended_part_size},
688 );
689 }
690  
691 # default content-type
692 $args->content_type ||= 'b2/x-auto';
693  
694 my $bucket_id = $self->b2_get_bucket_id($args->bucket_name);
695 if (!$bucket_id) {
696 return $self->error_tracker(
697 'error_message' => 'Can not upload to ' . $args->bucket_name . ' because bucket not found.',
698 );
699 }
700  
701 # kick off the upload in the API
702 my $response = $self->send_request(
703 'url' => 'b2_start_large_file',
704 'post_params' => {
705 'bucketId' => $bucket_id,
706 'fileName' => $args->new_file_name,
707 'contentType' => $args->content_type,
708 },
709 );
710  
711 # these are all needed for each b2_upload_part web call
712 my $large_file_id = $response->{fileId};
713 if (!$bucket_id) {
714 return $self->error_tracker(
715 'error_message' => 'Error in b2_upload_large_file for ' . $args->new_file_name,
716 );
717 }
718  
719 # open the large file
720 open(my $fh, $args->file_location);
721 my $remaining_file_size = $stat->size;
722 my $part_number = 1;
723  
724 # cycle thru each chunk of the file
725 my $size_sent = 0;
726 my @sha1_array = ();
727 while ($remaining_file_size >= 0) {
728 # how much to send?
729 if ($remaining_file_size < $self->{recommended_part_size} ) {
730 $size_sent = $remaining_file_size;
731 } else {
732 $size_sent = $self->apit_info->{recommended_part_size};
733 }
734  
735 # get the next upload url for this part
736 $self->send_request(
737 'url' => 'b2_get_upload_part_url',
738 'post_params' => {
739 'fileId' => $large_file_id,
740 },
741 );
742  
743 # read in that section of the file and prep the SHA
744 my $file_contents_part;
745 sysread $fh, $file_contents_part, $size_sent;
746 push(@sha1_array, sha1_hex( $file_contents_part ));
747  
748 # upload that part
749 $self->send_request(
750 'url' => $response->{uploadUrl},
751 'authorization' => $response->{authorizationToken},
752 'headers' => {
753 'X-Bz-Content-Sha1' => $sha1_array[-1],
754 'X-Bz-Part-Number' => $part_number,
755 'Content-Length' => $size_sent,
756 },
757 'file_contents' => $file_contents_part,
758 );
759  
760 # advance
761 $part_number++;
762 $remaining_file_size -= $self->api_info->{recommended_part_size};
763 }
764  
765 # close the file
766 close $fh;
767  
768 # and tell B2
769 $response = $self->send_request(
770 'url' => 'b2_finish_large_file',
771 'post_params' => {
772 'fileId' => $large_file_id,
773 'partSha1Array' => \@sha1_array,
774 },
775 );
776  
777 # phew, i'm tired...
778 return $self->current_status_is_not_ok ? 0 : $response->{fileId};
779 }
780  
781 1 1;
782  
783 __END__
784  
785 =head1 NAME
786  
787 Backblaze::B2V4 - Client library for the Backblaze B2 Cloud Storage Service V4 API.
788  
789 =head1 SYNOPSIS
790  
791 use Backblaze::B2V4;
792  
793 # create an API client object
794 my $b2 = Backblaze::B2V4->new(
795 application_key => $application_key,
796 application_key_id => $application_key_id,
797 );
798 # please encrypt/protect those keys when not in use!
799  
800 # let's say we have a B2 bucket called 'GingerAnna' and a JPG called 'ginger_was_perfect.jpg'.
801  
802 # upload a file from your file system
803 my $response = $b2->b2_upload_file(
804 bucket_name => 'GingerAnna',
805 file_location => '/path/to/ginger_was_perfect.jpg'
806 );
807  
808 # upload a file you have in a scalar
809 my $response = $b2->b2_upload_file(
810 bucket_name => 'GingerAnna',
811 new_file_name => 'ginger_was_perfect.jpg',
812 file_contents => $file_contents
813 );
814 # B2 file ID (fGUID) is now in $response->{fileId}
815 # Best to load $file_contents via Path::Tiny's slurp_raw() method
816  
817 # download that file to /opt/majestica/tmp
818 my $response = $b2->b2_download_file_by_name(
819 bucket_name => 'GingerAnna',
820 file_name => 'ginger_was_perfect.jpg',
821 save_to_location => '/opt/majestica/tmp'
822 );
823  
824 # if you would rather download with the 84-character GUID
825 my $response = $b2->b2_download_file_by_id(
826 file_id => 'X-Bz-File-Id GUID from above',
827 save_to_location => '/opt/majestica/tmp'
828 );
829
830 # For all of these $response is the output from the B2 V4 API
831
832 # to confirm all is well
833 my $all_is_well = $b2->current_status_is_not_ok != 1;
834 # or
835 my $all_is_well = $b2->current_status_is_ok());
836
837 # to get the latest error
838 print $b2->latest_error();
839 # if none, will be 'No error message found'
840  
841 =head1 DESCRIPTION / SET UP
842  
843 This module should help you create buckets and store/retrieve files in the
844 Backblaze B2 cloud storage service using V4 of their API.
845  
846 Backblaze makes it easy to sign up for B2 from here:
847  
848 https://www.backblaze.com/b2/sign-up.html
849  
850 Then enable the B2 service as per these instructions:
851  
852 https://www.backblaze.com/b2/docs/quick_account.html
853  
854 Next, visit the 'App Keys' section of the 'My Account' area, and look for
855 the 'Add a New Application Key' button to create an application key. You
856 will need a key with Read and Write access. Be sure to note the Application Key
857 ID as well as the Application Key itself. They do not show you that Application
858 Key again, so copy it immediately.
859  
860 Please store the Application Key pair in a secure way, preferably encrypted
861 when not in use by your software.
862  
863 =head2 b2_client Command Line Utility
864  
865 Backblaze::B2V4 includes the 'b2_client' command line utility to
866 easily download or upload files from B2. Please execute 'b2_client help'
867 for more details, and here are a few examples:
868  
869 # download a file to current directory
870 b2_client get MyPictures FamilyPhoto.jpg
871
872 # download a file to a target directory
873 b2_client get MyPictures FamilyPhoto.jpg /home/ginger/photos
874
875 # upload a file to B2
876 b2_client put MyPictures /home/ginger/photos/AnotherFamilyPhoto.jpg
877  
878 There is also an official command line utility from Backblaze that does a
879 whole lot more:
880  
881 https://www.backblaze.com/b2/docs/quick_command_line.html
882  
883 =head2 BackBlaze B2 also has a S3-compatible API
884  
885 Backblaze has added an S3-compatible API, which you can read about here:
886  
887 https://www.backblaze.com/b2/docs/s3_compatible_api.html
888  
889 They are continuing to support their native B2 API, so I will continue
890 to use and support this module. I have not tested the S3 modules with
891 Backblaze, but if you already have an S3 integration, it is worth
892 checking out how Paws::S3 or Awes::S3 works with Backblaze.
893  
894 =head2 Testing Your Credentials
895  
896 During install, this module will attempt to connect to B2 and download
897 a 16KB file into memory. To test using your B2 account
898 credentials, set these environmental varables prior to attempting
899 to install:
900  
901 B2_APP_KEY_ID - The application key ID for the key you wish to test.
902 B2_APP_KEY - The application key -- is never displayed in the B2 UI.
903 B2_ACCT_ID - Your account ID; will be the ID of your master key
904 B2_TEST_FILE_ID: The long (75+ char) GUID for your target file.
905  
906 The GUID for a file is displayed when you click on that file's name
907 in the 'Browse Files' section of the B2 UI.
908  
909 =head1 METHODS
910  
911 =head2 new
912  
913 Creates the B2 client object and initiates an API session with B2.
914  
915 Requires two arguments:
916 application_key => the Application Key from Backblaze,
917 application_key_id => the Application Key ID from Backblze,
918  
919 Returns your B2 client object.
920  
921 =head2 b2_download_file_by_id
922  
923 Retrieves a file plus metadata given the GUID of that file.
924 The 'file_id' argument is required and will be the file's GUID.
925 If you would like to auto-save the file, provide a path to an
926 existing directory via the 'save_to_location' argument.
927  
928 On success, will return the $response hashref with these keys:
929  
930 file_contents
931 content-length
932 content-type
933 x-bz-file-id
934 x-bz-file-name
935 x-bz-content-sha1
936  
937 See https://www.backblaze.com/b2/docs/b2_download_file_by_id.html
938  
939 =head2 b2_download_file_by_name
940  
941 Works like b2_download_file_by_id() except that it expects 'bucket_name'
942 and 'file_name' named arguments arguments.
943 If you would like to auto-save the file, provide a path to an
944 existing directory via the 'save_to_location' argument.
945  
946 See https://www.backblaze.com/b2/docs/b2_download_file_by_name.html
947  
948 =head2 b2_upload_file
949  
950 Uploads a new file into B2. Accepts these named arguments:
951  
952 bucket_name => required, name of destination bucket,
953 content_type => optional mime type; defaults to b2/x-auto,
954 file_location => optional, full path of file to upload incl name
955 new_file_name => optional, filename for file on B2
956 file_contents => optional scalar with file contents
957  
958 If you do not provide 'file_location', then you need to provide
959 'new_file_name' and 'file_contents' (or vice versa).
960 If you are going to use the 'file_contents' method, it's best
961 to load the scalar using the 'slurp_raw' method in Path::Tiny.
962 (I believe 'read_file' in File::Slurp will work, but have yet to test.)
963  
964 If successful, returns the GUID for the new file (aka the fileId); otherwise
965 returns 0.
966 See: https://www.backblaze.com/b2/docs/b2_upload_file.html
967  
968 Example 1: Uploading from a file on disk:
969  
970 my $file_id = $b2->b2_upload_file(
971 bucket_name => 'GingerAnna',
972 file_location => '/opt/majestica/tmp/ginger_was_perfect.jpg',
973 );
974  
975 Example 2: Uploading when the file is loaded into a scalar:
976  
977 my $file_id = $b2->b2_upload_file(
978 bucket_name => 'GingerAnna',
979 new_file_name => 'ginger_was_perfect.jpg',
980 file_contents => $file_contents
981 );
982  
983 =head2 b2_upload_large_file
984  
985 Uploads a large file into B2. Recommended for uploading files larger
986 than 100MB.
987  
988 Example:
989  
990 my $file_id = $b2->b2_upload_large_file(
991 bucket_name => 'GingerAnna',
992 file_location => '/opt/majestica/tmp/gingers_whole_life_story.mp4',
993 );
994  
995 =head2 b2_list_file_info
996  
997 Retrieves an arrayref hashrefs with file infomrmation for a bucket.
998 Backblaze calls if 'b2_list_file_names' but it really is for file info.
999 Limited to 10,000 file results per call, so you will may need to
1000 call repeatedly to retrieve all names.
1001  
1002 NOTE: You are billed per 1,000 results returned.
1003  
1004 Accepts these named arguments
1005  
1006 bucket_name => required, the name of the target bucket,
1007 prefix => optional, if seeking files that start with a given string,
1008 start_file_name => optional, the file name to start listing 10,000 files from
1009 delimiter => optional (default '/') used if you have folders within your bucket,
1010  
1011 See https://www.backblaze.com/b2/docs/b2_list_file_names.html ,
1012 especially the section for 'Response' to see what is included for those
1013 file info hashes.
1014  
1015 Basic call:
1016  
1017 my $files_ref = $b2->b2_list_file_names(
1018 bucket_name => 'MyBucketName'
1019 );
1020  
1021 =head2 b2_get_file_info
1022  
1023 Given a GUID for a file, will retrieve its info a $response hash
1024 See https://www.backblaze.com/b2/docs/b2_get_file_info.html
1025  
1026 my $response = $b2->b2_get_file_info(
1027 file_id => 'AN84_CHAR_GUID_FROM_B2'
1028 );
1029  
1030 =head2 b2_bucket_maker
1031  
1032 Creates a new bucket in your B2 account, given the name for the new
1033 bucket. The bucket type will be set to 'allPrivate'
1034  
1035 Returns 1 (success) or 0 (failure)
1036  
1037 Accepts named args:
1038  
1039 bucket_name => required, the name of the new bucket
1040 disable_encryption => optional, 1 or 0 and defaults to 0 --> have the encryption
1041  
1042 See: https://www.backblaze.com/b2/docs/b2_create_bucket.html
1043  
1044 Note that B2 bucket namess must be unique system-wide, not just your account.
1045 Select a name that willbe unique globally.
1046  
1047 Example:
1048  
1049 my $success = $b2->b2_bucket_maker(
1050 bucket_name => 'NewBucketName'
1051 );
1052  
1053 By default the new bucket will be set to use the 'Server-Side
1054 Encryption with Backblaze-Managed Keys (SSE-B2)' option
1055 described here: https://www.backblaze.com/b2/docs/server_side_encryption.html
1056 You can send a second param to disable that (not recommended):
1057  
1058 my $success = $b2->b2_bucket_maker(
1059 bucket_name => 'UnEncryptedBucketName',
1060 disable_encryption => 1
1061 );
1062
1063 Also, if your app key does not have the 'writeBucketEncryption' then
1064 encryption will be disabled.
1065  
1066 =head2 b2_delete_bucket
1067  
1068 Deletes a bucket from your B2 account, provided that it is empty.
1069  
1070 Requires the target bucket's name as the 'bucket_name' argument.
1071  
1072 Returns 1 (success) or 0 (failure)
1073  
1074 See: https://www.backblaze.com/b2/docs/b2_delete_bucket.html
1075  
1076 Example:
1077  
1078 my $success = $b2->b2_delete_bucket(
1079 bucket_name => 'DeletingBucketName'
1080 );
1081  
1082 =head2 b2_delete_file_version
1083  
1084 Deletes a version of a file, AKA a stored object. If you use unique
1085 file names for each file you upload, then one version equals one file.
1086 If you upload multiple files with the same name under a single bucket,
1087 you will create multiple versions of a particular file in B2.
1088  
1089 Required named args
1090  
1091 file_name => the name of the file
1092 file_id => the Backblaze GUID for the file
1093  
1094 Returns 1 (success) or 0 (failure)
1095  
1096 my $success = $b2->b2_delete_file_version(
1097 file_name => 'SomeFileName.ext',
1098 file_id => 'AN84_CHAR_GUID_FROM_B2'
1099 );
1100  
1101 =head2 b2_get_bucket_id
1102  
1103 If/when you need the ID for a bucket, call 'b2_get_bucket_id'
1104  
1105 Example:
1106  
1107 my $bucket_id = $b2->b2_get_bucket_id(
1108 bucket_name => 'MyBucketName',
1109 auto_create_bucket => 0 or 1,
1110 );
1111
1112 Pass 1 for 'auto_create_bucket' to make the bucket if one does not exist for your 'bucket_name'
1113 and return the new bucket ID. If you pass 0 for 'auto_create_bucket' and the bucket doesn't
1114 exist, you will receive back a 0.
1115  
1116 =head2 b2_get_upload_info
1117  
1118 Almost all the API calls use the Account Authorization Token for the
1119 authorization header, but the file uploader calls require a bucket-specific
1120 token and upload URL. You can retrieve these via b2_get_upload_info()
1121 with the bucket name as an argument.
1122  
1123 Example:
1124  
1125 my $results = $b2->b2_get_upload_info(
1126 bucket_name => 'MyBucketName'
1127 );
1128  
1129 The %$results hash now has 'upload_url' and 'authorization_token'
1130  
1131 Note: You have to call b2_get_upload_info on a bucket for each file
1132 upload operation. My b2_upload_file method does that for you, so that's
1133 just FYI if you roll your own.
1134  
1135 See: https://www.backblaze.com/b2/docs/b2_get_upload_info.html
1136  
1137 =head2 send_request
1138  
1139 send_request() handles all the communications with B2.
1140 You should be able to use this to make calls not explicitly
1141 provided by this library.
1142  
1143 If send_request() gets a 200 HTTP status from B2, then the call went
1144 great, $b2->current_status_is_not_ok will be 0, and
1145 the JSON response will be returned.
1146  
1147 If a 200 is not received from B2, $b2->current_status_is_not_ok
1148 will be 1, and you can find an error in $b2->latest_error()
1149  
1150 Note that the base URL for this API session will be stored
1151 under $b2->api_info->{api_url} so that you build a URL like so:
1152  
1153 $list_buckets_url = $b2->api_info->{api_url}.'/b2api/v4/b2_list_buckets';
1154  
1155 Example of a GET API request:
1156  
1157 my $response = $b2->send_request(
1158 url => 'https://SomeB2.API.URL?with=GETparams',
1159 );
1160  
1161 Example of a POST API request:
1162  
1163 my $response = $b2->send_request(
1164 url => 'https://SomeB2.API.URL',
1165 post_params => {
1166 param1_name => 'param1_value',
1167 param2_name => 'param2_value',
1168 param3_name => 'param3_value',
1169 },
1170 );
1171  
1172 See: https://www.backblaze.com/b2/docs/b2_list_buckets.html
1173  
1174 =head1 DEPENDENCIES
1175  
1176 This module requires:
1177  
1178 Cpanel::JSON::XS
1179 Digest::SHA
1180 HTTP::Request
1181 LWP::Protocol::https
1182 LWP::UserAgent
1183 Marlin
1184 MIME::Base64
1185 Path::Tiny
1186 URI::Escape
1187  
1188 =head1 SEE ALSO
1189  
1190 B2 API V4 Docs: https://www.backblaze.com/apidocs/b2-authorize-account
1191  
1192 Paws::S3 - If using Backblaze's S3-compatible API.
1193  
1194 =head1 AUTHOR / BUGS
1195  
1196 Eric Chernoff <eric@weaverstreet.net> - Please send me a note with any bugs or suggestions.
1197  
1198 ESTRABD <estrabd@cpan.org> - Enhanced b2_list_file_names() to fully use options and a great bugfix
1199 when using the 'file_contents' option in the b2_upload_file() method.
1200  
1201 =head1 LICENSE
1202  
1203 MIT License
1204  
1205 Copyright (c) 2026 Eric Chernoff
1206  
1207 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
1208  
1209 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
1210  
1211 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
↑ Summary Build »