/**
* Компонент облачного хранилища Яндекс Диск.
*/
class YandexDisk implements CloudInterface
{
/**
* @var string {@see https://oauth.yandex.ru OAuth токен}
*/
private string $oAuthToken;
/**
* @var resource
*/
private $streamContext;
/**
* @param string $oAuthToken OAuth токен
*/
public function __construct(string $oAuthToken)
{
$this->oAuthToken = $oAuthToken;
}
/**
* Возвращает контекст для запроса к API.
*
* @return resource
*/
private function getStreamContext()
{
if (this->streamContext === null) {
$this->streamContext = \stream_context_create([
'http' => [
'header' => ['Accept: application/json', 'Authorization: OAuth ' . $this->oAuthToken],
'timeout' => 5
]
]);
}
return $this->streamContext;
}
/**
* Возвращает результат запроса к API.
*
* @param string $pathSuffix URL path
* @param array $query URL query
* @return array
*/
private function apiRequest(string $pathSuffix, array $query): array
{
$url = 'https://cloud-api.yandex.net/v1/disk/' . $pathSuffix . '?' . \http_build_query($query);
$response = \file_get_contents($url, false, $this->getStreamContext());
return empty($response) ? [] : json_decode($response);
}
/**
* @inheritDoc
*/
public function getFiles(string $dir, int $offset = 0, int $limit = 100): array
{
$query = [
'fields' => 'resource_id,name,path,modified,size,type',
'limit' => $limit,
'offset' => $offset,
'media_type' => 'video'
];
$response = $this->apiRequest('resources/files', $query);
$files = $response['items'] ?? [];
foreach ($files as &$file) {
$file = [
'id' => $file['resource_id'],
'name' => $file['name'],
'path' => $file['path'],
'modified' => $file['modified'],
'size' => $file['size'] ?? 0,
'isDir' => $file['type'] === 'dir'
];
}
unset($file);
return $files;
}
/**
* @inheritDoc
*/
public function getPreview(string $file, $size = null): ?string
{
$query = ['fields' => 'preview', 'preview_crop' => 'false', 'preview_size' => $size ?? 'M', 'path' => $file];
$response = $this->apiRequest('resources', $query);
return $response['preview'] ?? null;
}
/**
* @inheritDoc
*/
public function getTempUrl(string $file): ?string
{
$response = $this->apiRequest('resources/download', ['fields' => 'href', 'path' => $file]);
return $response['href'] ?? null;
}
}