Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
65 changes: 41 additions & 24 deletions app/Actions/Promises/SetPromiseContentAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,80 +6,97 @@
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;

class SetPromiseContentAction
{
public function __construct(
protected ClearPromiseContentAction $clearPromiseContentAction,
) {}

/**
* @param string|UploadedFile|resource $content
*/
public function handle(PrintJobPromise $promise, mixed $content, ?string $name = null): void
{
if ($content instanceof UploadedFile) {
$this->handleUploadedFile($promise, $content, $name);
} elseif (is_resource($content)) {
$this->handleResource($promise, $content, $name);
} else {
$this->handleString($promise, $content, $name);
$attributes = $promise->getAttributes();
$previousFile = $promise->content_file;

try {
if ($content instanceof UploadedFile) {
$this->handleUploadedFile($promise, $content, $name);
} elseif (is_resource($content)) {
$this->handleResource($promise, $content, $name);
} else {
$this->handleString($promise, $content, $name);
}

if (! $promise->saveOrFail()) {
throw new RuntimeException('Unable to save promise content.');
}
} catch (Throwable $exception) {
if ($promise->content_file && $promise->content_file !== $previousFile) {
Storage::delete($promise->content_file);
}

$promise->setRawAttributes($attributes, true);

throw $exception;
}

if ($previousFile && $previousFile !== $promise->content_file) {
Storage::delete($previousFile);
}
}

protected function handleUploadedFile(PrintJobPromise $promise, UploadedFile $content, ?string $name = null): void
{
$this->clearPromiseContentAction->handle($promise);

$promise->content_file = $content->store('jobs');
$promise->content = null;
$promise->content_file = 'jobs/'.$content->hashName();
if (! $content->storeAs('jobs', $content->hashName())) {
throw new RuntimeException('Unable to store uploaded promise content.');
}
$promise->size = $content->getSize();
$promise->file_name ??= $content->getClientOriginalName();

if ($name) {
$promise->file_name = $name;
}

$promise->save();
}

protected function handleString(PrintJobPromise $promise, string $content, ?string $name = null): void
{
$this->clearPromiseContentAction->handle($promise);

if (strlen($content) < 1024 && ! preg_match('#[^\x20-\x7e\n]#', $content)) {
$promise->content = $content;
$promise->content_file = null;
} else {
$promise->content = null;
$promise->content_file = 'jobs/'.Str::random(40).'.dat';
Storage::put($promise->content_file, $content);
if (! Storage::put($promise->content_file, $content)) {
throw new RuntimeException('Unable to store promise content.');
}
}

if ($name) {
$promise->file_name = $name;
}

$promise->size = strlen($content);
$promise->save();
}

/**
* @param resource $content
*/
protected function handleResource(PrintJobPromise $promise, mixed $content, ?string $name = null): void
{
$this->clearPromiseContentAction->handle($promise);

$tmp_file = Str::random(40).'.dat';

$promise->content = null;
$promise->content_file = 'jobs/'.$tmp_file;
Storage::writeStream($promise->content_file, $content);
if (! Storage::writeStream($promise->content_file, $content)) {
throw new RuntimeException('Unable to store streamed promise content.');
}
$promise->size = Storage::size($promise->content_file);
$promise->file_name ??= $tmp_file;
if ($name) {
$promise->file_name = $name;
}

$promise->save();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public function update(Request $request, PrintJob $job)
{
$fields = $request->validate([
'status' => ['required', Rule::in(['printing', 'finished', 'failed'])],
'status_message' => ['required_if:status,failed'],
'status_message' => ['required_if:status,failed', 'nullable', 'string', 'max:255'],
]);

$job->status = $fields['status'];
Expand Down
25 changes: 16 additions & 9 deletions app/Http/Controllers/WebPrintApi/PrintDialogsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use RuntimeException;

class PrintDialogsController extends Controller
{
Expand Down Expand Up @@ -58,19 +59,25 @@ public function store(Request $request, PrintJobPromise $promise): PrintDialogRe

$validated = $request->validate([
'restricted_ip' => ['nullable', 'ip'],
'redirect_url' => ['nullable', 'url'],
'redirect_url' => ['nullable', 'string', 'url', 'max:255'],
'auto_print' => ['nullable', 'boolean'],
]);

if ($promise->PrintDialog !== null) {
$promise->PrintDialog->delete();
}
$dialog = $promise->getConnection()->transaction(function () use ($promise, $validated): PrintDialog {
if ($promise->PrintDialog !== null) {
$promise->PrintDialog->delete();
}

$dialog = new PrintDialog;
$dialog->auto_print = $validated['auto_print'] ?? true;
$dialog->redirect_url = $validated['redirect_url'] ?? null;
$dialog->restricted_ip = $validated['restricted_ip'] ?? null;
if (! $promise->PrintDialog()->save($dialog)) {
throw new RuntimeException('Unable to save print dialog.');
}

$dialog = new PrintDialog;
$dialog->auto_print = $validated['auto_print'] ?? true;
$dialog->redirect_url = $validated['redirect_url'] ?? null;
$dialog->restricted_ip = $validated['restricted_ip'] ?? null;
$promise->PrintDialog()->save($dialog);
return $dialog;
});

return new PrintDialogResource($dialog->fresh());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\StreamedResponse;
Expand Down Expand Up @@ -78,11 +79,15 @@ public function store(
if ($request->hasFile('content')) {
$file = $request->file('content');

Validator::make(['name' => $file->getClientOriginalName()], [
'name' => ['required', 'string', 'max:255'],
])->validate();

$setPromiseContentAction->handle($promise, $file);
} elseif ($request->has('content')) {
$validated = $request->validate([
'content' => 'required',
'name' => $promise->file_name ? 'nullable' : 'required',
'content' => ['required', 'string'],
'name' => [$promise->file_name ? 'nullable' : 'required', 'string', 'max:255'],
]);

$setPromiseContentAction->handle(
Expand All @@ -91,10 +96,14 @@ public function store(
name: $validated['name'] ?? $promise->file_name
);
} else {
$validated = Validator::make(['name' => $request->header('X-File-Name')], [
'name' => ['nullable', 'string', 'max:255'],
])->validate();

$setPromiseContentAction->handle(
promise: $promise,
content: $request->getContent(true),
name: $request->hasHeader('X-File-Name') && $request->header('X-File-Name') ? $request->header('X-File-Name') : null,
name: $validated['name'],
);
}

Expand Down
10 changes: 5 additions & 5 deletions app/Http/Controllers/WebPrintApi/PrintJobPromisesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,17 @@ public function store(
->pluck('ulid');

$validated = $request->validate([
'name' => ['required', 'string'],
'name' => ['required', 'string', 'max:255'],
'printer' => ['nullable', Rule::in($client_printers_ulids)],
'available_printers' => ['nullable', 'array'],
'available_printers.*' => ['string', Rule::in($client_printers_ulids)],
'type' => 'required',
'type' => ['required', 'string', 'max:255'],
'ppd_options' => ['nullable', 'array'],
'ppd_options.*' => ['required', 'string'],
'meta' => ['nullable', 'array'],
'meta.*' => ['required', 'string'],
'content' => 'nullable',
'file_name' => 'required_with:content',
'content' => ['nullable', $request->hasFile('content') ? 'file' : 'string'],
'file_name' => ['required_with:content', 'nullable', 'string', 'max:255'],
'headless' => ['nullable', 'boolean'],
]);

Expand Down Expand Up @@ -166,7 +166,7 @@ public function update(
$available_printers = $promise->AvailablePrinters()->pluck('ulid');
$validated = $request->validate([
'status' => ['nullable', 'in:ready'],
'name' => ['nullable', 'string'],
'name' => ['nullable', 'string', 'max:255'],
'printer' => ['nullable', Rule::in($available_printers)],
'ppd_options' => ['nullable', 'array'],
'ppd_options.*' => ['required', 'string'],
Expand Down
145 changes: 145 additions & 0 deletions tests/Feature/Actions/ReplacePromiseContentTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?php

namespace Tests\Feature\Actions;

use App\Actions\Promises\SetPromiseContentAction;
use App\Models\PrintJobPromise;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Tests\TestCase;

class ReplacePromiseContentTest extends TestCase
{
use RefreshDatabase;

private PrintJobPromise $promise;

protected function setUp(): void
{
parent::setUp();

Storage::fake('local');
Storage::put('jobs/original.dat', 'Original document');
$this->promise = PrintJobPromise::factory()->create([
'content' => null,
'content_file' => 'jobs/original.dat',
'file_name' => 'original.dat',
'size' => 17,
'print_job_id' => null,
])->refresh();
}

private function content(string $kind): mixed
{
return match ($kind) {
'inline' => 'New document',
'file' => str_repeat('New document', 100),
'upload' => UploadedFile::fake()->createWithContent('new.txt', 'New document'),
'stream' => $this->stream(),
};
}

private function stream(): mixed
{
$stream = fopen('php://temp', 'r+');
fwrite($stream, 'New document');
rewind($stream);

return $stream;
}

public static function contentKinds(): array
{
return [['inline'], ['file'], ['upload'], ['stream']];
}

private function assertOriginalDocumentIsIntact(array $attributes): void
{
$this->assertEquals($attributes, $this->promise->fresh()->getAttributes());
$this->assertSame('Original document', Storage::get('jobs/original.dat'));
$this->assertSame(['jobs/original.dat'], Storage::allFiles('jobs'));
}

#[DataProvider('contentKinds')]
public function test_database_failure_preserves_the_original_document_and_cleans_up_new_files(string $kind): void
{
$attributes = $this->promise->getAttributes();
Event::listen('eloquent.saved: '.PrintJobPromise::class, function (): void {
throw new RuntimeException('Simulated database failure');
});

$content = $this->content($kind);

try {
app(SetPromiseContentAction::class)->handle($this->promise, $content, 'new.txt');
$this->fail('Expected the database failure to propagate.');
} catch (RuntimeException $exception) {
$this->assertSame('Simulated database failure', $exception->getMessage());
} finally {
Event::forget('eloquent.saved: '.PrintJobPromise::class);
if (is_resource($content)) {
fclose($content);
}
}

$this->assertOriginalDocumentIsIntact($attributes);
}

#[DataProvider('contentKinds')]
public function test_successful_replacement_saves_new_content_before_removing_the_old_file(string $kind): void
{
$content = $this->content($kind);
Event::listen('eloquent.saving: '.PrintJobPromise::class, function (): void {
Storage::assertExists('jobs/original.dat');
});

try {
app(SetPromiseContentAction::class)->handle($this->promise, $content, 'new.txt');
} finally {
Event::forget('eloquent.saving: '.PrintJobPromise::class);
if (is_resource($content)) {
fclose($content);
}
}

$this->promise->refresh();
$expected = $kind === 'file' ? str_repeat('New document', 100) : 'New document';
$this->assertSame($expected, $this->promise->content ?? Storage::get($this->promise->content_file));
$this->assertEquals(strlen($expected), $this->promise->size);
$this->assertSame('new.txt', $this->promise->file_name);
Storage::assertMissing('jobs/original.dat');
}

#[DataProvider('failedWrites')]
public function test_storage_failure_preserves_the_original_document(string $kind, string $method): void
{
$attributes = $this->promise->getAttributes();
$content = $this->content($kind);
$disk = Mockery::mock(Storage::disk('local'));
$disk->shouldReceive($method)->once()->andReturn(false);
Storage::set('local', $disk);

try {
app(SetPromiseContentAction::class)->handle($this->promise, $content, 'new.txt');
$this->fail('Expected a storage failure.');
} catch (RuntimeException $exception) {
$this->assertStringContainsString('Unable to store', $exception->getMessage());
} finally {
if (is_resource($content)) {
fclose($content);
}
}

$this->assertOriginalDocumentIsIntact($attributes);
}

public static function failedWrites(): array
{
return [['file', 'put'], ['upload', 'putFileAs'], ['stream', 'writeStream']];
}
}
Loading
Loading