110 lines
2.4 KiB
PHP
110 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Nwb\MultiDownloaderClient;
|
|
|
|
class MultiDownloaderClient
|
|
{
|
|
private string $apiUrl = 'https://multi-dl.kub.nwb.fr';
|
|
private string $apiKey;
|
|
|
|
private array $files = [];
|
|
|
|
public function __construct(array $options = [])
|
|
{
|
|
$apiKey = $options['apiKey'] ?? getenv('MULTI_DOWNLOADER_API_KEY');
|
|
|
|
if (!$apiKey) {
|
|
throw new \InvalidArgumentException('API key is required');
|
|
}
|
|
|
|
$this->apiKey = $apiKey;
|
|
|
|
if (!empty($options['apiUrl'])) {
|
|
$this->apiUrl = $options['apiUrl'];
|
|
}
|
|
}
|
|
|
|
public function setFiles(array $files)
|
|
{
|
|
$this->files = [];
|
|
$this->addFiles($files);
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function addFile(FileRequest $file)
|
|
{
|
|
$this->files[] = $file;
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function addFiles(array $files)
|
|
{
|
|
foreach ($files as $file) {
|
|
$this->addFile($file);
|
|
}
|
|
|
|
return $this;
|
|
}
|
|
|
|
private function buildRequest(): array
|
|
{
|
|
return array_map(function (FileRequest $file) {
|
|
return $file->toArray();
|
|
}, $this->files);
|
|
}
|
|
|
|
public function downloadAsString(): string
|
|
{
|
|
return $this->sendRequest();
|
|
}
|
|
|
|
public function downloadTo(string $path): string
|
|
{
|
|
$response = $this->sendRequest([
|
|
CURLOPT_RETURNTRANSFER => false,
|
|
CURLOPT_FILE => fopen($path, 'w'),
|
|
]);
|
|
|
|
return $response;
|
|
}
|
|
|
|
public function htmlForm(): string
|
|
{
|
|
ob_start();
|
|
include __DIR__ . '/htmlForm.php';
|
|
return ob_get_clean();
|
|
}
|
|
|
|
private function sendRequest(array $options = []): string
|
|
{
|
|
$ch = curl_init();
|
|
|
|
$options = array_replace($options, [
|
|
CURLOPT_URL => $this->apiUrl . '/v2/zip',
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => json_encode($this->buildRequest()),
|
|
CURLOPT_HTTPHEADER => [
|
|
'Content-Type: application/json',
|
|
'Authorization: Bearer ' . $this->apiKey,
|
|
],
|
|
]);
|
|
|
|
curl_setopt_array($ch, $options);
|
|
|
|
$response = curl_exec($ch);
|
|
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
|
|
if ($httpCode !== 200) {
|
|
throw new MultiDownloaderException('Error while requesting API: ' . $response);
|
|
}
|
|
|
|
curl_close($ch);
|
|
|
|
return $response;
|
|
}
|
|
}
|