Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for file operations #103

Merged
merged 9 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions examples/FileSharing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

require_once(__DIR__ . '/../vendor/autoload.php');

use PubNub\PubNub;
use PubNub\PNConfiguration;

$channelName = "file-channel";
$fileName = "pn.gif";

$config = new PNConfiguration();
$config->setSubscribeKey(getenv('SUBSCRIBE_KEY', 'demo'));
$config->setPublishKey(getenv('PUBLISH_KEY', 'demo'));
$config->setUserId('example');

$pubnub = new PubNub($config);

// Sending file
// $fileHandle = fopen(__DIR__ . DIRECTORY_SEPARATOR . $fileName, "r");
// $sendFileResult = $pubnub->sendFile()
// ->channel($channelName)
// ->fileName($fileName)
// ->message("Hello from PHP SDK")
// ->fileHandle($fileHandle)
// ->sync();

// fclose($fileHandle);

// Listing files in the channel
$channelFiles = $pubnub->listFiles()->channel($channelName)->sync();
if ($channelFiles->getCount() > 0) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about introducing:
$fileCount = $channelFiles->getCount();
?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would improve readability

print("There are {$channelFiles->getCount()} files in the channel {$channelName}\n");
foreach ($channelFiles->getFiles() as $idx => $file) {
print("File[{$idx}]: {$file->getName()} with ID: {$file->getId()},"
. "size {$file->getSize()}, created at: {$file->getCreationTime()}\n");
}
} else {
print("There are no files in the channel {$channelName}\n");
}

$file = $channelFiles->getFiles()[0];

print('Getting download URL for the file...');
$downloadUrl = $pubnub->getFileDownloadUrl()
->channel($channelName)
->fileId($file->getId())
->fileName($file->getName())
->sync();

printf("To download the file use the following URL: %s\n", $downloadUrl->getFileUrl());

print("Downloading file...");
$downloadFile = $pubnub->downloadFile()
->channel($channelName)
->fileId($file->getId())
->fileName($file->getName())
->sync();
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . $file->getName(), $downloadFile->getFileContent());
print("done. File saved as: {$file->getName()}\n");

// deleting file
$deleteFile = $pubnub->deleteFile()
->channel($channelName)
->fileId($file->getId())
->fileName($file->getName())
->sync();

if ($deleteFile->getStatus() === 200) {
print("File deleted successfully\n");
} else {
print("Failed to delete file\n");
}
6 changes: 3 additions & 3 deletions src/PubNub/Endpoints/Access/Audit.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ public function sync()
}

/**
* @param array $json Decoded json
* @param array $result Decoded json
* @return PNAccessManagerAuditResult
*/
protected function createResponse($json)
protected function createResponse($result)
{
return PNAccessManagerAuditResult::fromJson($json['payload']);
return PNAccessManagerAuditResult::fromJson($result['payload']);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/PubNub/Endpoints/Access/Grant.php
Original file line number Diff line number Diff line change
Expand Up @@ -285,12 +285,12 @@ public function sync()
}

/**
* @param array $json
* @param array $result
* @return PNAccessManagerGrantResult
*/
public function createResponse($json)
public function createResponse($result)
{
return PNAccessManagerGrantResult::fromJson($json['payload']);
return PNAccessManagerGrantResult::fromJson($result['payload']);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ protected function buildPath()
}

/**
* @param array $json Decoded json
* @param array $result Decoded json
* @return PNChannelGroupsAddChannelResult
*/
protected function createResponse($json)
protected function createResponse($result)
{
return new PNChannelGroupsAddChannelResult();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ public function sync()
}

/**
* @param array $json Decoded json
* @param array $result Decoded json
* @return PNChannelGroupsListChannelsResult
*/
protected function createResponse($json)
protected function createResponse($result)
{
return PNChannelGroupsListChannelsResult::fromPayload(static::fetchPayload($json));
return PNChannelGroupsListChannelsResult::fromPayload(static::fetchPayload($result));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ public function sync()
}

/**
* @param array $json Decoded json
* @param array $result Decoded json
* @return PNChannelGroupsRemoveChannelResult
*/
protected function createResponse($json)
protected function createResponse($result)
{
return new PNChannelGroupsRemoveChannelResult();
}
Expand Down
4 changes: 2 additions & 2 deletions src/PubNub/Endpoints/ChannelGroups/RemoveChannelGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ public function sync()
}

/**
* @param array $json Decoded json
* @param array $result Decoded json
* @return PNChannelGroupsRemoveGroupResult
*/
protected function createResponse($json)
protected function createResponse($result)
{
return new PNChannelGroupsRemoveGroupResult();
}
Expand Down
80 changes: 48 additions & 32 deletions src/PubNub/Endpoints/Endpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,21 @@

abstract class Endpoint
{
protected const RESPONSE_IS_JSON = true;

/** @var PubNub */
protected $pubnub;

/** @var PNEnvelope */
protected $envelope;

protected $customHost = null;

/** @var array */
protected static $cachedTransports = [];

protected $followRedirects = true;

public function __construct(PubNub $pubnubInstance)
{
$this->pubnub = $pubnubInstance;
Expand All @@ -42,10 +48,10 @@ public function __construct(PubNub $pubnubInstance)
abstract protected function validateParams();

/**
* @param array $json Decoded json
* @param array $result Decoded json
* @return mixed
*/
abstract protected function createResponse($json);
abstract protected function createResponse($result);

/**
* @return int
Expand Down Expand Up @@ -321,20 +327,18 @@ protected function invokeRequestAndCacheIt()
*/
protected function requestOptions()
{
$options = [
return [
'timeout' => $this->getRequestTimeout(),
'connect_timeout' => $this->getConnectTimeout(),
'transport' => $this->getDefaultTransport(),
'transport' => $this->getTransport(),
'useragent' => 'PHP/' . PHP_VERSION,
'follow_redirects' => $this->followRedirects,
];
}

$transport = $this->pubnub->getConfiguration()->getTransport();

if ($transport) {
$options['transport'] = $transport;
}

return $options;
protected function getTransport()
{
return $this->pubnub->getConfiguration()->getTransport() ?? $this->getDefaultTransport();
}

/**
Expand All @@ -345,7 +349,7 @@ protected function invokeRequest()
$headers = array_merge($this->defaultHeaders(), $this->customHeaders());

$url = PubNubUtil::buildUrl(
$this->pubnub->getBasePath(),
$this->pubnub->getBasePath($this->customHost),
$this->buildPath(),
$this->buildParams()
);
Expand Down Expand Up @@ -459,28 +463,40 @@ protected function invokeRequest()
['method' => $this->getName(), 'statusCode' => $request->status_code]
);

// NOTICE: 1 == JSON_OBJECT_AS_ARRAY (hhvm doesn't support this constant)
$parsedJSON = json_decode($request->body, true, 512, 1);
$errorMessage = json_last_error_msg();

if (json_last_error()) {
$this->pubnub->getLogger()->error(
"Unable to decode JSON body: " . $request->body,
['method' => $this->getName()]
if (static::RESPONSE_IS_JSON) {
// NOTICE: 1 == JSON_OBJECT_AS_ARRAY (hhvm doesn't support this constant)
$parsedJSON = json_decode($request->body, true, 512, 1);
$errorMessage = json_last_error_msg();

if (json_last_error()) {
$this->pubnub->getLogger()->error(
"Unable to decode JSON body: " . $request->body,
['method' => $this->getName()]
);

return new PNEnvelope(null, $this->createStatus(
$statusCategory,
$request->body,
$responseInfo,
(new PubNubResponseParsingException())
->setResponseString($request->body)
->setDescription($errorMessage)
));
}

return new PNEnvelope(
$this->createResponse($parsedJSON),
$this->createStatus($statusCategory, $request->body, $responseInfo, null)
);
} else {
return new PNEnvelope(
$this->createResponse($request->body),
$this->createStatus($statusCategory, $request->body, $responseInfo, null)
);

return new PNEnvelope(null, $this->createStatus(
$statusCategory,
$request->body,
$responseInfo,
(new PubNubResponseParsingException())
->setResponseString($request->body)
->setDescription($errorMessage)
));
}

} elseif ($request->status_code === 307 && !$this->followRedirects) {
return new PNEnvelope(
$this->createResponse($parsedJSON),
$this->createResponse($request),
$this->createStatus($statusCategory, $request->body, $responseInfo, null)
);
} else {
Expand Down Expand Up @@ -572,7 +588,7 @@ protected function getAffectedUsers()
*/
private function getDefaultTransport()
{
$need_ssl = (0 === stripos($this->pubnub->getBasePath(), 'https://'));
$need_ssl = (0 === stripos($this->pubnub->getBasePath($this->customHost), 'https://'));
$capabilities = array('ssl' => $need_ssl);

$cap_string = serialize($capabilities);
Expand Down
77 changes: 77 additions & 0 deletions src/PubNub/Endpoints/FileSharing/DeleteFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace PubNub\Endpoints\FileSharing;

use PubNub\Enums\PNHttpMethod;
use PubNub\Enums\PNOperationType;
use PubNub\Models\Consumer\FileSharing\PNDeleteFileResult;
use PubNub\PubNubUtil;

class DeleteFile extends FileSharingEndpoint
{
protected const ENDPOINT_URL = "/v1/files/%s/channels/%s/files/%s/%s";

protected function createResponse($result)
{
return new PNDeleteFileResult($result);
}

/**
* @return int
*/
protected function getOperationType()
{
return PNOperationType::PNDeleteFileOperation;
}

/**
* @return bool
*/
protected function isAuthRequired()
{
return true;
}

/**
* @return null|string
*/
protected function buildData()
{
return null;
}

/**
* @return string
*/
protected function buildPath()
{
return sprintf(
self::ENDPOINT_URL,
$this->pubnub->getConfiguration()->getSubscribeKey(),
PubNubUtil::urlEncode($this->channel),
PubNubUtil::urlEncode($this->fileId),
PubNubUtil::urlEncode($this->fileName)
);
}

/**
* @return array
*/
protected function customParams()
{
return [];
}

/**
* @return string PNHttpMethod
*/
protected function httpMethod()
{
return PNHttpMethod::DELETE;
}

public function name()
{
return "Delete file";
}
}
Loading
Loading