Files
SealShare/app/Livewire/FileUploader.php
T
Andreas Reinhold / reiniandClaude Opus 5 5853f1f7d6 Give every page the share pages' layout, at one width
The pages were built five ways: two layouts, seven widths from 28 to
64rem and four heading styles. Every page now looks like the share
pages: a centred heading over one 40rem column of outlined cards, with
the floating toolbar below.

- <x-page> (components/page.blade.php) is the root of every page. It
  draws the h1 and its line (`brand` takes the site's logo, title and
  description from Admin settings), an optional `mark` and `navigation`
  slot, then the content. It has no width prop: every page is the same
  <x-pane width="narrow">.
- The sign-in, password reset, confirm, verify email, two-factor
  challenge, setup and system password pages move onto layouts/app with
  the brand heading and their form in a card titled with the task.
  layouts/auth, auth-header and the settings heading partial are gone,
  and so is the per-page width CSS.
- Settings put their section nav under the heading; the admin pages get
  a description line each. FileUploader and ShareDownload no longer pass
  the branding to their views.
- The admin dashboard's table needed about 49rem, so its shares are a
  list: created above the token, which opens the share, then files,
  size, downloads and expiry on two lines that wrap instead of clipping,
  and one delete button. A "Sort by" select replaces the column headers
  (newest, oldest, expiring soonest with never-expiring last, largest,
  most downloads, most files) and resets the page. The stats stay two
  by two. table.css and sort-header.css are no longer imported.
- Branding hints in Admin settings name every page the title shows on.
- Tests: PageTemplateTest renders every page once and checks one page
  template, one h1 and the width, and the brand heading with its
  fallbacks. FrameTest measures the page column instead of the auth
  card and the 64rem main; dashboard tests follow the list and the sort
  select, including expiry order. .ai/rules/views.md records <x-page>,
  the CHANGELOG notes the change and the website screenshots are
  regenerated.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 21:42:04 +02:00

213 lines
7.2 KiB
PHP

<?php
namespace App\Livewire;
use App\Models\Setting;
use App\Models\Share;
use App\Services\PasswordGeneratorService;
use App\Services\ShareService;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The upload page. The browser encrypts each file chunk by chunk and sends the chunks to
* UploadChunkController (resources/js/share-uploader.js); this component registers the files
* into a pending share, lists them and completes the share with its options.
*/
#[Layout('layouts.app')]
class FileUploader extends Component
{
/** The pending share this page uploads into: created with the first file, one per page load. */
#[Locked]
public ?string $pendingToken = null;
public bool $usePassword = false;
public string $password = '';
public string $password_confirmation = '';
public string $expiration = '7d';
public ?int $maxDownloads = null;
public function mount(): void
{
$this->expiration = Setting::get('default_expiration', '7d') ?: '7d';
}
/**
* Register the files a visitor chose and hand the browser what it encrypts and sends them
* with. A file an admin limit refuses gets `null` in its place and the reason under `files`.
*
* @param array<int, array{name?: mixed, size?: mixed, path?: mixed}> $files
* @return array<int, array{id: int, url: string, key: string, noncePrefix: string, chunkSize: int, chunkCount: int}|null>
*/
public function registerFiles(array $files, ShareService $shareService): array
{
$this->resetErrorBag('files');
$targets = [];
foreach ($files as $file) {
try {
$shareFile = $shareService->registerFile(
$this->pendingShare(),
(string) ($file['name'] ?? ''),
(int) ($file['size'] ?? -1),
isset($file['path']) ? (string) $file['path'] : null,
);
} catch (ValidationException $e) {
if (! $this->getErrorBag()->has('files')) {
$this->addError('files', $e->errors()['files'][0]);
}
$targets[] = null;
continue;
}
if ($this->pendingToken !== $shareFile->share->token) {
$this->pendingToken = $shareFile->share->token;
session()->push('pending_shares', $this->pendingToken);
}
$header = $shareService->readHeader($shareFile);
$targets[] = [
'id' => $shareFile->id,
'url' => Str::beforeLast(route('upload.chunk', ['shareFile' => $shareFile, 'index' => 0]), '/'),
'key' => $shareFile->share->encryption_key,
'noncePrefix' => bin2hex($header['noncePrefix']),
'chunkSize' => $header['chunkSize'],
'chunkCount' => $header['chunkCount'],
];
}
return $targets;
}
/**
* Take files out of the pending share, whether or not their upload finished.
*
* @param array<int, mixed> $fileIds
*/
public function removeFiles(array $fileIds, ShareService $shareService): void
{
$files = $this->pendingShare()?->files()->whereIn('id', array_map('intval', $fileIds))->get() ?? [];
foreach ($files as $file) {
$shareService->removeFile($file);
}
$this->resetErrorBag('files');
}
/**
* Fill in a generated password as protection is switched on, when the admin chose "Prefilled".
* A password already in the field stays.
*/
public function updatedUsePassword(bool $value): void
{
$passwordGenerator = app(PasswordGeneratorService::class);
if ($value && $this->password === '' && $passwordGenerator->mode() === 'prefill') {
$this->password = $passwordGenerator->generate();
}
}
public function generatePassword(PasswordGeneratorService $passwordGenerator): void
{
if ($passwordGenerator->mode() === 'off') {
return;
}
$this->password = $passwordGenerator->generate();
$this->resetErrorBag('password');
}
public function createShare(ShareService $shareService): void
{
$rules = [];
if (! Setting::get('allow_never_expire', false)) {
$rules['expiration'] = ['required', 'string', 'in:1h,24h,48h,7d,14d,30d'];
}
if ($this->usePassword) {
$rules['password'] = ['required', 'string', 'min:8'];
}
if ($rules !== []) {
$this->validate($rules, [
'expiration.required' => __('An expiration time is required.'),
]);
}
$pendingShare = $this->pendingShare();
if ($pendingShare === null) {
$this->addError('files', __('Please select at least one file to upload.'));
return;
}
$share = $shareService->completeShare($pendingShare, [
'password' => $this->usePassword ? $this->password : null,
'expires_at' => match ($this->expiration) {
'1h' => now()->addHour(),
'24h' => now()->addDay(),
'48h' => now()->addDays(2),
'7d' => now()->addWeek(),
'14d' => now()->addDays(14),
'30d' => now()->addMonth(),
default => null,
},
'max_downloads' => $this->maxDownloads ?: null,
]);
session()->put('pending_shares', array_values(array_diff(session('pending_shares', []), [$share->token])));
// The page the upload leads to offers the password once more, next to the link; it is
// never stored in the clear, so this flash is the only way it gets there.
if ($this->usePassword) {
session()->flash('share_password', [
'token' => $share->token,
'password' => Crypt::encryptString($this->password),
]);
}
$this->redirect(route('share.created', $share), navigate: true);
}
public function render(): mixed
{
$shareService = app(ShareService::class);
$pendingFiles = $this->pendingShare()?->files()->orderBy('id')->get() ?? collect();
return view('livewire.file-uploader', [
'pendingFiles' => $pendingFiles,
'allFilesUploaded' => $pendingFiles->isNotEmpty() && $pendingFiles->every(fn ($file): bool => $file->completed_at !== null),
'isStorageFull' => $shareService->isStorageFull(),
'allowNeverExpire' => (bool) Setting::get('allow_never_expire', false),
'passwordGeneratorMode' => app(PasswordGeneratorService::class)->mode(),
]);
}
/**
* This page's pending share, while it is still pending and this session started it.
*/
private function pendingShare(): ?Share
{
if ($this->pendingToken === null || ! in_array($this->pendingToken, session('pending_shares', []), true)) {
return null;
}
return Share::query()->where('token', $this->pendingToken)->whereNull('completed_at')->first();
}
}