294 lines
10 KiB
PHP
294 lines
10 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Support\IriksStorage;
|
|
|
|
use Illuminate\Http\Client\PendingRequest;
|
|
use Illuminate\Http\Client\Response;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Facades\Crypt;
|
|
use Illuminate\Support\Facades\Http;
|
|
use IriksIT\Manager\Exceptions\MediaStorageException;
|
|
use Psr\Http\Message\StreamInterface;
|
|
use Throwable;
|
|
|
|
/**
|
|
* Talks to the IriksIT API (the `/storage` part of it): logs in with an account, keeps the token and the refresh token
|
|
* (encrypted) in the cache, renews them, and stores, opens, describes and deletes files. The account needs the
|
|
* `storage.read` and `storage.write` permissions. Every failure is a MediaStorageException; what the API says goes into
|
|
* its message (never an address, a token or a password).
|
|
*/
|
|
class Client
|
|
{
|
|
private const TOKEN = 'manager.iriksit.token';
|
|
|
|
private const REFRESH = 'manager.iriksit.refresh';
|
|
|
|
/** @param array{url?: string|null, email?: string|null, password?: string|null, timeout?: int|string|null} $config */
|
|
public function __construct(private readonly array $config) {}
|
|
|
|
/** Whether an address and an account are set at all. */
|
|
public function isConfigured(): bool
|
|
{
|
|
return $this->value('url') !== '' && $this->value('email') !== '' && $this->value('password') !== '';
|
|
}
|
|
|
|
/**
|
|
* Store a file. The `id` that comes back is the only handle to it afterwards.
|
|
*
|
|
* @param resource $stream
|
|
* @return array{id: string, size: int, mime_type: string|null, checksum: string|null}
|
|
*
|
|
* @throws MediaStorageException
|
|
*/
|
|
public function store($stream, string $filename): array
|
|
{
|
|
$response = $this->call(fn (PendingRequest $request) => $request->attach('file', $stream, $filename)->post($this->url('/storage'), ['priority' => 'normal']));
|
|
$data = $response->json('data');
|
|
|
|
if ($response->failed() || ! is_array($data) || ! is_string($data['id'] ?? null) || $data['id'] === '') {
|
|
throw $this->failure('store a file', $response);
|
|
}
|
|
|
|
return [
|
|
'id' => $data['id'],
|
|
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
|
|
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
|
|
'checksum' => is_string($data['checksum'] ?? null) ? $data['checksum'] : null,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* The content of a file as a stream; read it and close it.
|
|
*
|
|
* @throws MediaStorageException with status 404 when the API does not know the file
|
|
*/
|
|
public function open(string $id): StreamInterface
|
|
{
|
|
$response = $this->call(fn (PendingRequest $request) => $request->withOptions(['stream' => true])->get($this->url('/storage/'.rawurlencode($id).'/download')));
|
|
|
|
if ($response->status() !== 200) {
|
|
throw $this->failure('download a file', $response);
|
|
}
|
|
|
|
return $response->toPsrResponse()->getBody();
|
|
}
|
|
|
|
/**
|
|
* What the API knows of a file, or null when it does not know it.
|
|
*
|
|
* @return array{size: int, mime_type: string|null, created_at: string|null}|null
|
|
*
|
|
* @throws MediaStorageException
|
|
*/
|
|
public function details(string $id): ?array
|
|
{
|
|
$response = $this->call(fn (PendingRequest $request) => $request->get($this->url('/storage/'.rawurlencode($id))));
|
|
|
|
if ($response->status() === 404) {
|
|
return null;
|
|
}
|
|
|
|
$data = $response->json('data');
|
|
|
|
if ($response->failed() || ! is_array($data)) {
|
|
throw $this->failure('read a file', $response);
|
|
}
|
|
|
|
return [
|
|
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
|
|
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
|
|
'created_at' => is_string($data['created_at'] ?? null) ? $data['created_at'] : null,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Delete a file. One the API no longer knows counts as deleted.
|
|
*
|
|
* @throws MediaStorageException
|
|
*/
|
|
public function delete(string $id): void
|
|
{
|
|
$response = $this->call(fn (PendingRequest $request) => $request->delete($this->url('/storage/'.rawurlencode($id))));
|
|
|
|
if ($response->failed() && $response->status() !== 404) {
|
|
throw $this->failure('delete a file', $response);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Whether the account can log in at all: the check behind a "test the connection" button.
|
|
*
|
|
* @throws MediaStorageException
|
|
*/
|
|
public function check(): void
|
|
{
|
|
$this->token();
|
|
}
|
|
|
|
/**
|
|
* What the tokens of pieces of work cost, as the API worked it out with the price list and the euro rate of each day
|
|
* (`POST /tools/ai/cost`, permission `ai.pricing`). A row it has no price or rate for is left out; null when it cannot answer.
|
|
*
|
|
* @param list<array{reference: string, model: string, date: string, tokens: array<string, int>}> $items
|
|
* @return array<string, array{usd: float, eur: float, usd_per_eur: float}>|null by reference
|
|
*/
|
|
public function tokenCosts(array $items): ?array
|
|
{
|
|
if (! $this->isConfigured() || $items === []) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
$response = $this->call(fn (PendingRequest $request) => $request->timeout(15)->post($this->url('/tools/ai/cost'), ['items' => $items]));
|
|
} catch (MediaStorageException) {
|
|
return null;
|
|
}
|
|
|
|
if ($response->failed()) {
|
|
return null;
|
|
}
|
|
|
|
$costs = [];
|
|
$answer = $response->json('data.items');
|
|
|
|
foreach (is_array($answer) ? $answer : [] as $item) {
|
|
if (! is_array($item)) {
|
|
continue;
|
|
}
|
|
|
|
$reference = $item['reference'] ?? null;
|
|
$usd = is_array($item['usd'] ?? null) ? ($item['usd']['total'] ?? null) : null;
|
|
$rate = is_array($item['exchange_rate'] ?? null) ? ($item['exchange_rate']['usd_per_eur'] ?? null) : null;
|
|
|
|
if (is_string($reference) && is_numeric($usd) && is_numeric($item['eur'] ?? null) && is_numeric($rate) && (float) $rate > 0) {
|
|
$costs[$reference] = ['usd' => (float) $usd, 'eur' => (float) $item['eur'], 'usd_per_eur' => (float) $rate];
|
|
}
|
|
}
|
|
|
|
return $costs;
|
|
}
|
|
|
|
/**
|
|
* Runs a call with the current token. A 401 means the token was revoked on the API's side: forget it, log in
|
|
* again and try once more.
|
|
*
|
|
* @param \Closure(PendingRequest): Response $call
|
|
*
|
|
* @throws MediaStorageException
|
|
*/
|
|
private function call(\Closure $call): Response
|
|
{
|
|
try {
|
|
$response = $call($this->request($this->token()));
|
|
|
|
if ($response->status() !== 401) {
|
|
return $response;
|
|
}
|
|
|
|
Cache::forget(self::TOKEN);
|
|
Cache::forget(self::REFRESH);
|
|
|
|
return $call($this->request($this->token()));
|
|
} catch (MediaStorageException $e) {
|
|
throw $e;
|
|
} catch (Throwable) {
|
|
throw new MediaStorageException('The IriksIT storage could not be reached.');
|
|
}
|
|
}
|
|
|
|
private function request(string $token): PendingRequest
|
|
{
|
|
$timeout = $this->config['timeout'] ?? null;
|
|
|
|
return Http::acceptJson()->withoutRedirecting()->withToken($token)->connectTimeout(5)->timeout(is_numeric($timeout) ? (int) $timeout : 300);
|
|
}
|
|
|
|
/** @throws MediaStorageException */
|
|
private function token(): string
|
|
{
|
|
$token = $this->cached(self::TOKEN);
|
|
|
|
if ($token !== null) {
|
|
return $token;
|
|
}
|
|
|
|
$refresh = $this->cached(self::REFRESH);
|
|
|
|
if ($refresh !== null) {
|
|
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)->withToken($refresh)->post($this->url('/auth/refresh'));
|
|
|
|
if ($response->successful() && ($kept = $this->keep($response->json('data'))) !== null) {
|
|
return $kept;
|
|
}
|
|
|
|
Cache::forget(self::REFRESH);
|
|
}
|
|
|
|
if (! $this->isConfigured()) {
|
|
throw new MediaStorageException('No IriksIT account is set for the storage (address, email and password).');
|
|
}
|
|
|
|
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)
|
|
->post($this->url('/auth/login'), ['email' => $this->value('email'), 'password' => $this->value('password')]);
|
|
|
|
if ($response->failed()) {
|
|
throw new MediaStorageException("The IriksIT login failed (HTTP {$response->status()}).", $response->status());
|
|
}
|
|
|
|
return $this->keep($response->json('data')) ?? throw new MediaStorageException('The IriksIT API sent a login answer without a token.');
|
|
}
|
|
|
|
/** Remembers the tokens of a login answer until they expire (a minute early) and returns the access token. */
|
|
private function keep(mixed $data): ?string
|
|
{
|
|
if (! is_array($data) || ! is_string($data['token'] ?? null) || $data['token'] === '' || ! is_string($data['expire'] ?? null)) {
|
|
return null;
|
|
}
|
|
|
|
Cache::put(self::TOKEN, Crypt::encryptString($data['token']), Carbon::parse($data['expire'])->subMinute());
|
|
|
|
if (is_string($data['refresh_token'] ?? null) && is_string($data['refresh_expire'] ?? null)) {
|
|
Cache::put(self::REFRESH, Crypt::encryptString($data['refresh_token']), Carbon::parse($data['refresh_expire'])->subMinute());
|
|
}
|
|
|
|
return $data['token'];
|
|
}
|
|
|
|
private function cached(string $key): ?string
|
|
{
|
|
$value = Cache::get($key);
|
|
|
|
try {
|
|
return is_string($value) ? Crypt::decryptString($value) : null;
|
|
} catch (Throwable) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private function failure(string $action, Response $response): MediaStorageException
|
|
{
|
|
$reason = $response->json('message');
|
|
$detail = is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : '';
|
|
$retry = $response->header('Retry-After');
|
|
|
|
return new MediaStorageException(
|
|
"The IriksIT storage could not {$action} (HTTP {$response->status()}{$detail}).",
|
|
$response->status(),
|
|
is_numeric($retry) ? (int) $retry : null,
|
|
);
|
|
}
|
|
|
|
private function url(string $path): string
|
|
{
|
|
return rtrim($this->value('url'), '/').$path;
|
|
}
|
|
|
|
private function value(string $key): string
|
|
{
|
|
$value = $this->config[$key] ?? '';
|
|
|
|
return is_string($value) ? trim($value) : '';
|
|
}
|
|
}
|