This commit is contained in:
deploy-bot committed 2026-12-05 15:01:51 +00:00
commit 574aed3a9a
287 files changed
+19547

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
<?php
namespace IriksIT\Manager\Support\IriksStorage;
use GuzzleHttp\Psr7\StreamWrapper;
use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Support\Names;
use League\Flysystem\Config;
use League\Flysystem\DirectoryAttributes;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToCreateDirectory;
use League\Flysystem\UnableToDeleteDirectory;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToReadFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToSetVisibility;
use League\Flysystem\UnableToWriteFile;
use Psr\Http\Message\StreamInterface;
/**
* A Laravel disk (`driver` => `iriksit`) whose files live at the IriksIT API. The API knows files by an id of its own, not
* by a path, so every path that is written is remembered next to that id (table `storage_files`). A path that has no entry
* and no slash is taken for an id itself: that is how media rows that were made by a site's own code (the id as location)
* keep working. There are no folders, no visibility and no listing.
*/
class Adapter implements FilesystemAdapter
{
public function __construct(private readonly Client $client) {}
public function fileExists(string $path): bool
{
$id = $this->id($path);
if ($id === null) {
return false;
}
try {
return $this->client->details($id) !== null;
} catch (MediaStorageException $e) {
throw UnableToRetrieveMetadata::create($path, 'exists', $e->getMessage(), $e);
}
}
public function directoryExists(string $path): bool
{
return false;
}
public function write(string $path, string $contents, Config $config): void
{
$stream = fopen('php://temp', 'r+b');
fwrite($stream, $contents);
rewind($stream);
try {
$this->writeStream($path, $stream, $config);
} finally {
// The HTTP client closes what it sent itself.
if (is_resource($stream)) {
fclose($stream);
}
}
}
public function writeStream(string $path, $contents, Config $config): void
{
try {
$stored = $this->client->store($contents, basename($path));
} catch (MediaStorageException $e) {
throw UnableToWriteFile::atLocation($path, $e->getMessage(), $e);
}
DB::table($this->table())->updateOrInsert(['path' => $path], ['remote_id' => $stored['id']]);
}
public function read(string $path): string
{
$stream = $this->readStream($path);
$contents = stream_get_contents($stream);
is_resource($stream) && fclose($stream);
return $contents === false ? throw UnableToReadFile::fromLocation($path) : $contents;
}
public function readStream(string $path)
{
try {
return StreamWrapper::getResource($this->openFile($path));
} catch (MediaStorageException $e) {
throw UnableToReadFile::fromLocation($path, $e->getMessage(), $e);
}
}
/**
* The content of a file as it comes in (nothing is kept here first, so a video starts playing at once). `$kind` (image, video, audio
* or pdf) lets the API answer with a placeholder when it cannot serve the file; that travels in the exception.
*
* @throws MediaStorageException with status 404 when there is no such file
*/
public function openFile(string $path, ?string $kind = null): StreamInterface
{
$id = $this->id($path) ?? throw new MediaStorageException('There is no such file.', 404);
return $this->client->open($id, $kind);
}
public function delete(string $path): void
{
$id = $this->id($path);
if ($id === null) {
return;
}
try {
$this->client->delete($id);
} catch (MediaStorageException $e) {
throw UnableToDeleteFile::atLocation($path, $e->getMessage(), $e);
}
DB::table($this->table())->where('path', $path)->delete();
}
public function deleteDirectory(string $path): void
{
throw UnableToDeleteDirectory::atLocation($path, 'The IriksIT storage has no folders.');
}
public function createDirectory(string $path, Config $config): void
{
throw UnableToCreateDirectory::atLocation($path, 'The IriksIT storage has no folders.');
}
public function setVisibility(string $path, string $visibility): void
{
throw UnableToSetVisibility::atLocation($path, 'The IriksIT storage has no visibility.');
}
public function visibility(string $path): FileAttributes
{
throw UnableToRetrieveMetadata::visibility($path, 'The IriksIT storage has no visibility.');
}
public function mimeType(string $path): FileAttributes
{
$details = $this->details($path, 'mime_type');
return new FileAttributes($path, null, null, null, $details['mime_type'] ?? throw UnableToRetrieveMetadata::mimeType($path));
}
public function lastModified(string $path): FileAttributes
{
$created = $this->details($path, 'last_modified')['created_at'] ?? null;
return new FileAttributes($path, null, null, $created !== null ? strtotime($created) ?: null : throw UnableToRetrieveMetadata::lastModified($path));
}
public function fileSize(string $path): FileAttributes
{
return new FileAttributes($path, $this->details($path, 'file_size')['size']);
}
/** @return iterable<FileAttributes|DirectoryAttributes> */
public function listContents(string $path, bool $deep): iterable
{
return [];
}
public function move(string $source, string $destination, Config $config): void
{
throw UnableToMoveFile::fromLocationTo($source, $destination);
}
public function copy(string $source, string $destination, Config $config): void
{
throw UnableToCopyFile::fromLocationTo($source, $destination);
}
/** @return array{size: int, mime_type: string|null, created_at: string|null} */
private function details(string $path, string $what): array
{
$id = $this->id($path) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
try {
return $this->client->details($id) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
} catch (MediaStorageException $e) {
throw UnableToRetrieveMetadata::create($path, $what, $e->getMessage(), $e);
}
}
/** The id the API gave to what was written at this path, or the path itself when it looks like an id. */
private function id(string $path): ?string
{
$id = DB::table($this->table())->where('path', $path)->value('remote_id');
if (is_string($id)) {
return $id;
}
return $path !== '' && ! str_contains($path, '/') ? $path : null;
}
private function table(): string
{
return Names::table('storage_files');
}
}
+311
View File
@@ -0,0 +1,311 @@
<?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.
*
* `$kind` (image, video, audio or pdf) tells the API what is expected: when the file cannot be served it then sends a placeholder of that
* kind instead of an error, and that travels along in the exception.
*
* @throws MediaStorageException with status 404 when the API does not know the file
*/
public function open(string $id, ?string $kind = null): StreamInterface
{
$response = $this->call(fn (PendingRequest $request) => $request->withHeaders($kind !== null ? ['X-Media-Kind' => $kind] : [])->withOptions(['stream' => true])->get($this->url('/storage/'.rawurlencode($id).'/download')));
if ($response->status() !== 200) {
throw $this->failure('download a file', $response, withPlaceholder: true);
}
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, bool $withPlaceholder = false): MediaStorageException
{
$retry = $response->header('Retry-After');
$fallback = $response->header('X-Media-Fallback');
$type = $response->header('Content-Type');
// The API sent a placeholder instead of the file: the header says so, and the type is one a browser may show. Its body is that picture, not a message.
if ($withPlaceholder && preg_match('/^[a-z-]{1,30}$/', $fallback) === 1 && preg_match('#^(image/png|video/mp4|audio/mpeg|application/pdf)$#', $type) === 1) {
return new MediaStorageException(
"The IriksIT storage could not {$action} (HTTP {$response->status()}: {$fallback}).",
$response->status(),
is_numeric($retry) ? (int) $retry : null,
$response->toPsrResponse()->getBody(),
$type,
$fallback,
);
}
$reason = $response->json('message');
$detail = is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : '';
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) : '';
}
}