Skip to content

Commit

Permalink
added tests for some upload files util methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Nickbahson committed Mar 6, 2023
1 parent db6d8ab commit f224215
Show file tree
Hide file tree
Showing 7 changed files with 273 additions and 101 deletions.
104 changes: 58 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,56 +31,68 @@ $this->b2Client = new BackblazeClient($b2_configs);

* Uploading small files.
```php
// Steps
// Authorize requests
// Get the upload url + the authorizationToken
// Upload the file (b2_upload_file)
$b2_auth = $this->b2Client->b2AuthorizeAccount();
// Required from b2_auth
$auth_token = $b2_auth->authorizationToken;
$api_url = $b2_auth->apiUrl;

$file_name = '51863901_1591128994364639_5533062884642328214_n.jpg';
$key = 'tasks/'. $file_name;
// Assuming your files are stored in the '/uploads/', change to fit your folders.
$local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name;

$upload_details = $this->b2Client->b2GetUploadUrl($api_url, $auth_token);
$upload_file = $this->b2Client->b2UploadFile($key, $local_file, $upload_details->uploadUrl, $upload_details->authorizationToken);
var_dump($upload_details);
var_dump($upload_file);
die('HERE TOO');
// Steps

// Authorize requests

// Get the upload url + the authorizationToken

// Upload the file (b2_upload_file)

$b2_auth = $this->b2Client->b2AuthorizeAccount();

// Required from b2_auth

$auth_token = $b2_auth->authorizationToken;

$api_url = $b2_auth->apiUrl;


$file_name = '51863901_1591128994364639_5533062884642328214_n.jpg';

$key = 'a-file-folder/'. $file_name;
// Assuming your files are stored in the '/uploads/', change to fit your folders.

$local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name;


$upload_details = $this->b2Client->b2GetUploadUrl($api_url, $auth_token);

$upload_file = $this->b2Client->b2UploadFile($key, $local_file, $upload_details->uploadUrl, $upload_details->authorizationToken);

var_dump($upload_details);

var_dump($upload_file);

die('HERE TOO');
```


* Uploading large files (multipart).
```php
// Steps
//
//
//
$b2_auth = $this->b2Client->b2AuthorizeAccount();
// Required from b2_auth
$auth_token = $b2_auth->authorizationToken;
$api_url = $b2_auth->apiUrl;

$file_name = 'BULLET TRAIN - Official Trailer (HD).mp4';
$key = 'tasks/'. $file_name;
// Assuming your files are stored in the '/uploads/', change to fit your folders.
$local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name;

$start_upload_file = $this->b2Client->b2StartLargeFile($api_url, $auth_token, $key);
$fileId = $start_upload_file->fileId;

// From here, you can save the values required in b2UploadChunks($local_file, $auth_token, $api_url, $fileId);
// below, and later fire that action via a cron job, to make content editing easier (take less time) maybe.

// upload chuncks
$large_upload_res = $this->b2Client->b2UploadChunks($local_file, $auth_token, $api_url, $fileId);
// Delete local file maybe
// unlink( $local_file );

var_dump($large_upload_res);
die('DONE for a large file');
// Steps
//
//
//
$b2_auth = $this->b2Client->b2AuthorizeAccount();
// Required from b2_auth
$auth_token = $b2_auth->authorizationToken;
$api_url = $b2_auth->apiUrl;

$file_name = 'BULLET TRAIN - Official Trailer (HD).mp4';
$key = 'a-folder/'. $file_name;
// Assuming your files are stored in the '/uploads/', change to fit your folders.
$local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name;

$start_upload_file = $this->b2Client->b2StartLargeFile($api_url, $auth_token, $key);
$fileId = $start_upload_file->fileId// From here, you can save the values required in b2UploadChunks($local_file, $auth_token, $api_url, $fileId);
// below, and later fire that action via a cron job, to make content editing easier (take less time) maybe.

// upload chunks
$large_upload_res = $this->b2Client->b2UploadChunks($local_file, $auth_token, $api_url, $fileId);
// Delete local file maybe
// unlink( $local_file );
var_dump($large_upload_res);
die('DONE for a large file');

```
8 changes: 7 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
"Flaircore\\Backblaze\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Flaircore\\Backblaze\\Tests": "tests/"
}
},
"authors": [
{
"name": "Nicholas Njogu",
Expand All @@ -25,6 +30,7 @@
"ext-json": "*"
},
"require-dev": {
"monolog/monolog": "^3.3"
"monolog/monolog": "^3.3",
"phpunit/phpunit": "^10.0"
}
}
15 changes: 15 additions & 0 deletions example.phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php"
cacheResult="false"
>
<testsuites>
<testsuite name="Unit Tests">
<directory>tests/Unit</directory>
</testsuite>
</testsuites>
<php>
<ini name="display_errors" value="On" />
<ini name="display_warnings" value="On" />
<ini name="display_startup_errors" value="On" />
</php>
</phpunit>
106 changes: 56 additions & 50 deletions src/Clients/BackblazeClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ final public function b2ListUnfinishedLargeFiles($api_url, $account_auth_token){
* @throws \Exception
*/
final public function b2AuthorizeAccount(){
$application_key_id = B2_API_KEY;
$application_key = B2_API_SECRET;
$application_key_id = $this->b2Configs['B2_API_KEY'];
$application_key = $this->b2Configs['B2_API_SECRET'];
$credentials = base64_encode($application_key_id . ":" . $application_key);
$url = self::BASE_URL ."b2_authorize_account";

Expand All @@ -78,51 +78,6 @@ final public function b2AuthorizeAccount(){
}
}

/**
* @param $api_url
* @param $auth_token
* @param $key
* The file name of the file to be uploaded
*
* @return mixed
* @throws \Exception
*/
final public function b2StartLargeFile($api_url, $auth_token, $key) {
// The content type of the file. See b2_start_large_file documentation for more information.
$content_type = "b2/x-auto";

// Provided by b2_create_bucket, b2_list_buckets
$bucket_id = $this->b2Configs['B2_BUCKET_ID'];

// Construct the JSON to post
$data = array("fileName" => $key, "bucketId" => $bucket_id, "contentType" => $content_type);
$post_fields = json_encode($data);
$headers = [
'Accept' => 'application/json',
'Authorization' => [$auth_token]
];

try {
$client = $this->client();
$res = $client->postAsync($api_url . "/b2api/v2/b2_start_large_file", [
'headers' => $headers,
'body' => $post_fields,
]
)->wait();

if ($res->getStatusCode() == 200) {

return json_decode($res->getBody());
} else {
throw new \Exception("Error making request ". $res->getBody());
}

} catch (\Throwable $ex) {
throw new \Exception("Error making request ". $ex->getMessage());
}

}

/**
* Gets an URL to use for uploading files.
* https://www.backblaze.com/b2/docs/b2_get_upload_url.html
Expand Down Expand Up @@ -208,7 +163,7 @@ final public function b2GetUploadPartUrl($api_url, $auth_token, $file_id) {
*
* @return mixed
*/
final public function b2UploadFile($file_name, $local_file, $upload_url, $upload_auth_token, ) {
final public function b2UploadFile($file_name, $local_file, $upload_url, $upload_auth_token ) {

$client = $this->client();

Expand Down Expand Up @@ -241,6 +196,56 @@ final public function b2UploadFile($file_name, $local_file, $upload_url, $upload

}

/**
* @param $api_url
* @param $auth_token
* @param $key
* The file name of the file to be uploaded
*
* @return mixed
* @throws \Exception
*/
final public function b2StartLargeFile($api_url, $auth_token, $key) {
// The content type of the file. See b2_start_large_file documentation for more information.
$content_type = "b2/x-auto";

// Provided by b2_create_bucket, b2_list_buckets
$bucket_id = $this->b2Configs['B2_BUCKET_ID'];

// Construct the JSON to post
$data = [
"fileName" => $key,
"bucketId" => $bucket_id,
"contentType" => $content_type
];

$post_fields = json_encode($data);
$headers = [
'Accept' => 'application/json',
'Authorization' => [$auth_token]
];

try {
$client = $this->client();
$res = $client->postAsync($api_url . "/b2api/v2/b2_start_large_file", [
'headers' => $headers,
'body' => $post_fields,
]
)->wait();

if ($res->getStatusCode() == 200) {

return json_decode($res->getBody());
} else {
throw new \Exception("Error making request ". $res->getBody());
}

} catch (\Throwable $ex) {
throw new \Exception("Error making request ". $ex->getMessage());
}

}

/**
* Uploads chucks as well as finish the upload.
* https://www.backblaze.com/b2/docs/b2_upload_part.html
Expand Down Expand Up @@ -331,10 +336,10 @@ final public function b2UploadChunks($local_file, $auth_token, $api_url, $file_i

// Finish the upload

$data = array(
$data = [
"fileId" => $file_id,
"partSha1Array" => $sha1_of_parts
);
];

$headers = [
'Accept' => 'application/json',
Expand Down Expand Up @@ -364,4 +369,5 @@ private function curlReadFile($curl_rsrc, $file_pointer, $length) {
return fread($file_pointer, $length);
}


}
6 changes: 2 additions & 4 deletions src/Clients/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
trait HttpClient {
private $MAX_RETRIES = 5;

private $BASE_URL = 'https://api.backblazeb2.com/b2api/v2/';

/**
* @var Client
*/
Expand Down Expand Up @@ -46,8 +44,8 @@ public function __construct() {
$stack->push(Middleware::retry($decider, $delay));

$this->httpClient = new Client([
'base_uri' => 'https://api.backblazeb2.com/b2api/v2/',
//'handler' => $stack,
//'base_uri' => 'https://api.backblazeb2.com/b2api/v2/',
'handler' => $stack,
]);
}

Expand Down
Loading

0 comments on commit f224215

Please sign in to comment.