From cb9c4deb22681ef16bb4458de6ed90a5c4675c34 Mon Sep 17 00:00:00 2001 From: Christoph Rumpel Date: Sun, 22 Nov 2026 20:09:21 +0000 Subject: [PATCH 1/2] feat: add short videos to ordinary commits People can attach one video, up to 60 seconds and 100 MB, to an ordinary commit. The browser uploads it straight to private storage, a job on the `videos` queue re-encodes it with FFmpeg to an H.264 MP4 of up to Full HD plus a poster, and Commit unlocks once it is ready. Video commits always wait for a moderator, since the AI check only reads text and images, and they show in the moderation queue right away. Files are served only through an endpoint that checks access, re-encoded without their metadata, and deleted with their commit or account. Videos are not available in replies, quotes, scheduled commits, remotes, organization posts or guild boards yet. --- .agents/setup | 4 +- .github/workflows/tests.yml | 3 + KNOWLEDGE_BASE.md | 9 + PRODUCT.md | 2 +- README.md | 2 + app/Actions/CreateCommit.php | 15 +- app/Actions/CreateCommitVideo.php | 27 ++ app/Actions/CreateExport.php | 17 ++ app/Actions/DeleteCommitContent.php | 7 + app/Actions/DeleteCommitVideo.php | 25 ++ app/Actions/DeleteUser.php | 10 +- app/Actions/UpdateCommitAiDecision.php | 4 + app/Actions/UpdateCommitVideoProcessing.php | 27 ++ app/Actions/UpdateCommitVideoUpload.php | 17 ++ app/Enums/CommitVideoStatus.php | 13 + app/Http/Controllers/CommitController.php | 2 +- .../Controllers/CommitVideoController.php | 36 +++ .../CommitVideoPlaybackController.php | 32 ++ .../CommitVideoProcessingController.php | 18 ++ .../CommitVideoUploadController.php | 20 ++ app/Http/Controllers/ModerationController.php | 3 +- .../Requests/CreateCommitReplyRequest.php | 1 + app/Http/Requests/CreateCommitRequest.php | 15 +- .../CreateCommitVideoProcessingRequest.php | 44 +++ .../Requests/CreateCommitVideoRequest.php | 22 ++ .../CreateConversationMessageRequest.php | 1 + .../Requests/CreateScheduledCommitRequest.php | 1 + .../Requests/DeleteCommitVideoRequest.php | 26 ++ .../ShowCommitVideoPlaybackRequest.php | 31 ++ app/Http/Requests/ShowCommitVideoRequest.php | 26 ++ .../UpdateCommitVideoUploadRequest.php | 31 ++ app/Http/Resources/CommitResource.php | 8 + app/Jobs/ModerateCommit.php | 2 +- app/Jobs/ProcessCommitVideo.php | 116 ++++++++ app/Jobs/PruneCommitVideos.php | 52 ++++ app/Models/Commit.php | 10 +- app/Models/CommitVideo.php | 68 +++++ app/Queries/CommitBuilder.php | 10 +- app/Rules/ReadyCommitVideo.php | 26 ++ app/Services/CommitVideos.php | 67 +++++ config/video.php | 8 + database/factories/CommitVideoFactory.php | 20 ++ ...0_22_120000_create_commit_videos_table.php | 28 ++ resources/js/components/commit-card.tsx | 4 + resources/js/components/commit-composer.tsx | 101 +++++-- resources/js/components/commit-thread.tsx | 2 + .../js/components/commit-video-picker.tsx | 225 ++++++++++++++ resources/js/components/commit-video.tsx | 276 ++++++++++++++++++ resources/js/components/quoted-commit.tsx | 16 +- resources/js/hooks/use-commit-video.ts | 215 ++++++++++++++ resources/js/types/commit.ts | 13 + routes/console.php | 2 + routes/web.php | 16 + .../Controllers/Api/CommitControllerTest.php | 3 + .../Controllers/Api/LogControllerTest.php | 1 + .../Controllers/CommitVideoControllerTest.php | 176 +++++++++++ .../Controllers/ExportControllerTest.php | 1 + tests/Fixtures/commit-video.mp4 | Bin 0 -> 16839 bytes tests/Unit/Actions/CreateExportTest.php | 25 ++ .../Unit/Actions/DeleteCommitContentTest.php | 28 ++ tests/Unit/Actions/DeleteUserTest.php | 30 ++ tests/Unit/Jobs/ProcessCommitVideoTest.php | 114 ++++++++ tests/Unit/Jobs/PruneCommitVideosTest.php | 83 ++++++ tests/Unit/Queries/CommitBuilderTest.php | 9 +- 64 files changed, 2206 insertions(+), 40 deletions(-) create mode 100644 app/Actions/CreateCommitVideo.php create mode 100644 app/Actions/DeleteCommitVideo.php create mode 100644 app/Actions/UpdateCommitVideoProcessing.php create mode 100644 app/Actions/UpdateCommitVideoUpload.php create mode 100644 app/Enums/CommitVideoStatus.php create mode 100644 app/Http/Controllers/CommitVideoController.php create mode 100644 app/Http/Controllers/CommitVideoPlaybackController.php create mode 100644 app/Http/Controllers/CommitVideoProcessingController.php create mode 100644 app/Http/Controllers/CommitVideoUploadController.php create mode 100644 app/Http/Requests/CreateCommitVideoProcessingRequest.php create mode 100644 app/Http/Requests/CreateCommitVideoRequest.php create mode 100644 app/Http/Requests/DeleteCommitVideoRequest.php create mode 100644 app/Http/Requests/ShowCommitVideoPlaybackRequest.php create mode 100644 app/Http/Requests/ShowCommitVideoRequest.php create mode 100644 app/Http/Requests/UpdateCommitVideoUploadRequest.php create mode 100644 app/Jobs/ProcessCommitVideo.php create mode 100644 app/Jobs/PruneCommitVideos.php create mode 100644 app/Models/CommitVideo.php create mode 100644 app/Rules/ReadyCommitVideo.php create mode 100644 app/Services/CommitVideos.php create mode 100644 config/video.php create mode 100644 database/factories/CommitVideoFactory.php create mode 100644 database/migrations/2026_10_22_120000_create_commit_videos_table.php create mode 100644 resources/js/components/commit-video-picker.tsx create mode 100644 resources/js/components/commit-video.tsx create mode 100644 resources/js/hooks/use-commit-video.ts create mode 100644 tests/Feature/Controllers/CommitVideoControllerTest.php create mode 100644 tests/Fixtures/commit-video.mp4 create mode 100644 tests/Unit/Actions/CreateExportTest.php create mode 100644 tests/Unit/Jobs/ProcessCommitVideoTest.php create mode 100644 tests/Unit/Jobs/PruneCommitVideosTest.php diff --git a/.agents/setup b/.agents/setup index ba51abe73b..c9bf6665f7 100755 --- a/.agents/setup +++ b/.agents/setup @@ -26,10 +26,10 @@ if ((${#legacy_packages[@]})); then sudo env DEBIAN_FRONTEND=noninteractive apt-get remove -y "${legacy_packages[@]}" fi -step 'Checking system packages (PHP 8.5 and PostgreSQL 18)' +step 'Checking system packages (PHP 8.5, PostgreSQL 18 and FFmpeg)' packages=(php8.5-cli php8.5-curl php8.5-gd php8.5-intl php8.5-mbstring php8.5-pgsql php8.5-xml php8.5-zip php8.5-pcov postgresql-18 - postgresql-18-pgvector) + postgresql-18-pgvector ffmpeg) missing=() for package in "${packages[@]}"; do if ! dpkg-query -W -f='${Status}' "$package" 2>/dev/null | grep -qx 'install ok installed'; then diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8095738a71..17ce79127e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -155,6 +155,9 @@ jobs: if: steps.build-cache.outputs.cache-hit != 'true' run: bun run build + - name: Install Video Encoder + run: sudo apt-get update && sudo apt-get install -y ffmpeg + - name: PHP Tests run: | mkdir -p tmp/coverage diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index c860972480..a4b2531a93 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -25,6 +25,7 @@ This file documents the platform's features, stack, and stories. Feature entries - [Draft previews](#draft-previews) - [Stashed drafts](#stashed-drafts) - [Images and descriptions](#images-and-descriptions) + - [Short videos](#short-videos) - [Links, link cards, and embedded players](#links-link-cards-and-embedded-players) - [Replies and threads](#replies-and-threads) - [Quoting commits](#quoting-commits) @@ -295,6 +296,14 @@ Attach up to **three JPEG, PNG, or WebP images** to a commit or reply. Each imag Sources: [image picker](resources/js/components/commit-image-picker.tsx), [image limits](app/Actions/CreateCommitImages.php), [image processing](app/Actions/CreateImageFiles.php), [attachment validation](app/Http/Requests/CreateCommitRequest.php), [photo controller](app/Http/Controllers/CommitPhotoController.php). +### Short videos + +Ordinary commits in the browser can attach one MP4, MOV, or WebM video, up to **60 seconds** and **100 MB**. Videos cannot be combined with images or a poll, and are not available in replies, quotes, scheduled commits, remotes, commits posted as an organization, or guild boards. Text is optional; an optional description can explain the video in up to 1,000 characters. + +Keep the composer open while the video uploads and prepares for playback. You can keep writing, but Commit becomes available only when the video is ready. Videos do not survive closing the draft: choose the file again when returning. A submitted video commit waits for review before other people can see it. Playback starts only when you press play, with controls to pause, seek, mute, replay, and go fullscreen. Uploaded videos are re-encoded and their original metadata removed; the original upload is not retained after processing. + +Sources: [video composer](resources/js/components/commit-video-picker.tsx), [video validation](app/Http/Requests/CreateCommitRequest.php), [video processing](app/Services/CommitVideos.php). + ### Links, link cards, and embedded players Each link in a commit or reply counts as at most **23 characters** toward the 4,000-character allowance; shorter links count at their actual length. This also applies to quotes, scheduled commits, previews, and terminal and app submissions. The full URL is stored and followed directly, not through a redirect service. Prose URLs longer than **2,048 characters** are rejected, including the inferred `https://` scheme for bare domains. Code still counts literally toward the 4,000-character allowance. Bodies are additionally capped at 40,000 raw characters to bound storage and processing. Private messages and issue drafts keep their existing literal character limits. diff --git a/PRODUCT.md b/PRODUCT.md index c0fc1d6156..d21de46457 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -31,7 +31,7 @@ Developers who left X or Bluesky, or are thinking about it, and want a feed with What exists, one line each (details in the knowledge base): -- **Commits:** text with code, images, link cards and embedded players, or a poll; replies, quotes, threads, scheduling, translation. +- **Commits:** text with code, images, a short video, link cards and embedded players, or a poll; replies, quotes, threads, scheduling, translation. - **Logs:** Following, Latest, and Trending. - **Engagement:** follows, stars, saved commits, pins, mentions, and pastéis (an opt-in daily allowance of pastries). - **Profiles:** mirrored from GitHub, with an activity graph, streaks, achievements, a Unix rank, and a live marker while you stream on YouTube. diff --git a/README.md b/README.md index 7b894077f4..3c48c39a0a 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ composer dev Run `composer test` before opening a pull request. +Video uploads also need FFmpeg and FFprobe, both locally and in the tests. Videos are encoded on the `videos` queue, so run `php artisan queue:work --queue=videos` alongside `composer dev`. Locally, uploads go through PHP, so set `post_max_size` and `upload_max_filesize` above 100M in your `php.ini`. + ### Live updates Pages hear about changes through any server speaking the Pusher protocol, such as Laravel Cloud's WebSockets or a self-hosted Reverb. By default `BROADCAST_CONNECTION=log` sends nothing anywhere and every page polls as before. To try them locally, run a Pusher-protocol server on your machine, set `BROADCAST_CONNECTION=reverb` with the `REVERB_*` variables pointing at it, set the matching `VITE_REVERB_*` variables, and rebuild the assets: the `VITE_` ones are read at build time. Tests always use the `null` broadcaster. diff --git a/app/Actions/CreateCommit.php b/app/Actions/CreateCommit.php index eda2c2f220..d725e6e812 100644 --- a/app/Actions/CreateCommit.php +++ b/app/Actions/CreateCommit.php @@ -8,6 +8,7 @@ use App\Dto\ThreadEngagement; use App\Enums\CommitStatus; use App\Enums\CommitUpdate; +use App\Enums\CommitVideoStatus; use App\Enums\UserUpdate; use App\Events\CommitsUpdated; use App\Events\ProfilesUpdated; @@ -21,6 +22,7 @@ use App\Jobs\ReplyAsTom; use App\Jobs\UnfurlLink; use App\Models\Commit; +use App\Models\CommitVideo; use App\Models\Guild; use App\Models\LinkPreview; use App\Models\Organization; @@ -65,7 +67,7 @@ public function __construct( * @param array $imageDescriptions * @param array $replyRecipients */ - public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $quotedCommit = null, array $images = [], array $imageDescriptions = [], bool|string $linkPreview = true, ?NewPoll $poll = null, array $replyRecipients = [], ?Organization $organization = null, ?Guild $guild = null): Commit + public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $quotedCommit = null, array $images = [], array $imageDescriptions = [], bool|string $linkPreview = true, ?NewPoll $poll = null, array $replyRecipients = [], ?Organization $organization = null, ?Guild $guild = null, ?string $videoId = null, ?string $videoDescription = null): Commit { $url = match ($linkPreview) { true => $this->urls->first($body), @@ -73,11 +75,14 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit default => $linkPreview, }; - return DB::transaction(function () use ($user, $body, $parent, $quotedCommit, $images, $imageDescriptions, $url, $poll, $replyRecipients, $organization, $guild): Commit { + return DB::transaction(function () use ($user, $body, $parent, $quotedCommit, $images, $imageDescriptions, $url, $poll, $replyRecipients, $organization, $guild, $videoId, $videoDescription): Commit { if ($guild instanceof Guild && Guild::query()->whereKey($guild->id)->sharedLock()->firstOrFail()->user_id === null) { throw new GuildPaused; } + // Claim under the same lock as cancellation, so two tabs cannot attach the same upload. + $video = $videoId === null ? null : CommitVideo::query()->where('user_id', $user->id) + ->where('status', CommitVideoStatus::Ready)->whereNull('commit_id')->lockForUpdate()->findOrFail($videoId); $linkPreview = $url === null ? null : $this->createLinkPreview->handle($url); $createdAt = now(); $hasGoodReputation = $user->hasGoodReputation(); @@ -91,7 +96,7 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit 'mentions' => [...$replyRecipients, ...$mentions], 'parent_id' => $parent?->id, 'root_id' => $parent?->threadRootId(), - 'status' => $user->isAdmin() || $hasGoodReputation ? CommitStatus::Approved : CommitStatus::Pending, + 'status' => $video === null && ($user->isAdmin() || $hasGoodReputation) ? CommitStatus::Approved : CommitStatus::Pending, 'link_preview_id' => $linkPreview?->id, 'quoted_commit_id' => $quotedCommit?->id, 'hot_score' => $this->theAlgorithm->score($createdAt, ThreadEngagement::none()), @@ -101,6 +106,8 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $this->createCommitTopics->handle($commit, $this->mentionedOrganizations->get($body, $mentions)); $this->createCommitImages->handle($commit, $images, $imageDescriptions); + $video?->update(['commit_id' => $commit->id, 'description' => $videoDescription]); + if ($poll instanceof NewPoll) { $this->createPoll($commit, $poll); } @@ -141,7 +148,7 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit LinkCommitTopics::dispatchFor($commit); ProcessCommitHeadlines::dispatchFor($commit); - if ($commit->status === CommitStatus::Pending && ! $hasGoodReputation) { + if ($video === null && $commit->status === CommitStatus::Pending && ! $hasGoodReputation) { dispatch(new ModerateCommit($commit))->afterCommit(); } diff --git a/app/Actions/CreateCommitVideo.php b/app/Actions/CreateCommitVideo.php new file mode 100644 index 0000000000..9fe9160774 --- /dev/null +++ b/app/Actions/CreateCommitVideo.php @@ -0,0 +1,27 @@ +}} */ + public function handle(User $user, int $size): array + { + $video = CommitVideo::query()->create(['user_id' => $user->id, 'size' => $size]); + $upload = config('filesystems.disks.'.config()->string('filesystems.default').'.driver') === 'local' + ? ['url' => route('commit-video-upload.update', $video), 'headers' => ['Content-Type' => 'application/octet-stream']] + : Storage::temporaryUploadUrl($video->path('source'), now()->addMinutes(15), ['ContentType' => 'application/octet-stream', 'ContentLength' => $size]); + + $upload = new Fluent($upload); + + return ['video' => $video->refresh(), 'upload' => ['url' => $upload->string('url')->value(), 'method' => 'PUT', 'headers' => Arr::except($upload->array('headers'), ['Host', 'Content-Length'])]]; + } +} diff --git a/app/Actions/CreateExport.php b/app/Actions/CreateExport.php index 26ff673e4a..6f67ead3a3 100644 --- a/app/Actions/CreateExport.php +++ b/app/Actions/CreateExport.php @@ -9,6 +9,7 @@ use App\Models\Commit; use App\Models\CommitImage; use App\Models\CommitReport; +use App\Models\CommitVideo; use App\Models\Conversation; use App\Models\ConversationParticipant; use App\Models\Device; @@ -46,6 +47,7 @@ * active_days: Generator, * commits: Generator>, * organization_commits: Generator>, + * videos: Generator>, * polls: Generator, * poll_votes: Generator, * stars: Generator, @@ -130,6 +132,7 @@ public function handle(User $user): array 'active_days' => $this->activeDays($user), 'commits' => $this->commits($user), 'organization_commits' => $this->organizationCommits($user), + 'videos' => $this->videos($user), 'polls' => $this->polls($user), 'poll_votes' => $this->pollVotes($user), 'stars' => $this->stars($user), @@ -261,6 +264,20 @@ private function commits(User $user): Generator } } + /** @return Generator> */ + private function videos(User $user): Generator + { + foreach (CommitVideo::query()->where('user_id', $user->id)->lazyById(500) as $video) { + yield [ + ...$video->toArray(), + 'commit_id' => $video->commit_id, + 'size' => $video->size, + 'created_at' => $video->created_at->toIso8601String(), + 'updated_at' => $video->updated_at->toIso8601String(), + ]; + } + } + /** * What the user posted for organizations, which is theirs to read back, though the organizations' own, even once * GitHub no longer has the organization and its commits lost their author. diff --git a/app/Actions/DeleteCommitContent.php b/app/Actions/DeleteCommitContent.php index 8e1882c326..9c74d47724 100644 --- a/app/Actions/DeleteCommitContent.php +++ b/app/Actions/DeleteCommitContent.php @@ -5,6 +5,7 @@ namespace App\Actions; use App\Models\Commit; +use App\Models\CommitVideo; use App\Models\Headline; use App\Models\LinkPreview; use Illuminate\Support\Facades\DB; @@ -29,6 +30,12 @@ public function handle(Commit $commit): void $imagePaths = $commit->images()->pluck('path')->all(); + CommitVideo::query()->where('commit_id', $commit->id)->lockForUpdate()->each(function (CommitVideo $video): void { + Storage::delete($video->path('source')); + Storage::deleteDirectory('commit-videos/'.$video->id); + $video->delete(); + }); + $commit->images()->delete(); $commit->poll()->delete(); diff --git a/app/Actions/DeleteCommitVideo.php b/app/Actions/DeleteCommitVideo.php new file mode 100644 index 0000000000..00e0418041 --- /dev/null +++ b/app/Actions/DeleteCommitVideo.php @@ -0,0 +1,25 @@ +whereNull('commit_id')->lockForUpdate()->find($video->id); + + if ($video !== null) { + Storage::deleteDirectory('commit-videos/'.$video->id); + Storage::delete($video->path('source')); + $video->delete(); + } + }); + } +} diff --git a/app/Actions/DeleteUser.php b/app/Actions/DeleteUser.php index a9d45b8d98..6a2522c9bf 100644 --- a/app/Actions/DeleteUser.php +++ b/app/Actions/DeleteUser.php @@ -12,6 +12,7 @@ use App\Models\Commit; use App\Models\CommitImage; use App\Models\CommitReport; +use App\Models\CommitVideo; use App\Models\Conversation; use App\Models\ConversationParticipant; use App\Models\Guild; @@ -77,7 +78,14 @@ public function handle(User $user): void // Report creation holds shared reporter and commit locks until its attachment paths are saved. $guilds = Guild::query()->where('user_id', $user->id)->orderBy('id')->lockForUpdate()->get(); $guildMembers = DB::table('guild_preferences')->whereIn('guild_id', $guilds->modelKeys())->whereNot('user_id', $user->id)->pluck('user_id'); - $imagePaths = [...$this->reportImagePaths($user), ...$this->imagePaths($user), ...$this->scheduledImagePaths($user), ...$this->messageImagePaths($user), ...$this->messageVoicePaths($user), ...$this->guildSubmissionIconPaths($user)]; + // Locked so an encoder about to publish its result finds the video gone. The rows go with the user and their commits. + $videoPaths = CommitVideo::query() + ->where(fn (Builder $query) => $query->where('user_id', $user->id)->orWhereIn('commit_id', $this->touchedCommits($user)->select('id'))) + ->lockForUpdate() + ->get() + ->flatMap(fn (CommitVideo $video): array => [$video->path('source'), $video->path('video.mp4'), $video->path('poster.jpg')]) + ->all(); + $imagePaths = [...$this->reportImagePaths($user), ...$this->imagePaths($user), ...$this->scheduledImagePaths($user), ...$this->messageImagePaths($user), ...$this->messageVoicePaths($user), ...$this->guildSubmissionIconPaths($user), ...$videoPaths]; resolve(DeleteStoredFiles::class)->retain($imagePaths); DB::table('commit_topics')->whereIn('commit_id', $this->touchedCommits($user)->select('id'))->delete(); diff --git a/app/Actions/UpdateCommitAiDecision.php b/app/Actions/UpdateCommitAiDecision.php index 42cde72036..18e1f7bc58 100644 --- a/app/Actions/UpdateCommitAiDecision.php +++ b/app/Actions/UpdateCommitAiDecision.php @@ -38,6 +38,10 @@ public function __construct( */ public function handle(Commit $commit): void { + if ($commit->video()->exists()) { + return; + } + $images = array_values($commit->images->map( fn (CommitImage $image): string => 'data:image/webp;base64,'.base64_encode((string) Storage::get($image->path)), )->all()); diff --git a/app/Actions/UpdateCommitVideoProcessing.php b/app/Actions/UpdateCommitVideoProcessing.php new file mode 100644 index 0000000000..56b236c18b --- /dev/null +++ b/app/Actions/UpdateCommitVideoProcessing.php @@ -0,0 +1,27 @@ +lockForUpdate()->findOrFail($video->id); + + if ($video->status === CommitVideoStatus::Uploading) { + $video->update(['status' => CommitVideoStatus::Processing]); + dispatch(new ProcessCommitVideo($video->id))->afterCommit(); + } + + return $video; + }); + } +} diff --git a/app/Actions/UpdateCommitVideoUpload.php b/app/Actions/UpdateCommitVideoUpload.php new file mode 100644 index 0000000000..12d1e9e139 --- /dev/null +++ b/app/Actions/UpdateCommitVideoUpload.php @@ -0,0 +1,17 @@ +path('source'), $contents); + } +} diff --git a/app/Enums/CommitVideoStatus.php b/app/Enums/CommitVideoStatus.php new file mode 100644 index 0000000000..e143203c7a --- /dev/null +++ b/app/Enums/CommitVideoStatus.php @@ -0,0 +1,13 @@ +organization(); try { - $commit = $action->handle($user, $request->string('body')->value(), quotedCommit: $request->quotedCommit(), images: $request->images(), imageDescriptions: $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), organization: $organization, guild: $request->guild()); + $commit = $action->handle($user, $request->string('body')->value(), quotedCommit: $request->quotedCommit(), images: $request->images(), imageDescriptions: $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), organization: $organization, guild: $request->guild(), videoId: $request->videoId(), videoDescription: $request->videoDescription()); } catch (GuildPaused) { return back()->withErrors(['guild_handle' => 'This guild is paused until it has a moderator.']); } diff --git a/app/Http/Controllers/CommitVideoController.php b/app/Http/Controllers/CommitVideoController.php new file mode 100644 index 0000000000..07586dca98 --- /dev/null +++ b/app/Http/Controllers/CommitVideoController.php @@ -0,0 +1,36 @@ +json($action->handle($user, $request->integer('size')), 201); + } + + public function show(ShowCommitVideoRequest $request, CommitVideo $commitVideo): JsonResponse + { + return response()->json(['video' => $commitVideo])->header('Cache-Control', 'private, no-store'); + } + + public function destroy(DeleteCommitVideoRequest $request, CommitVideo $commitVideo, DeleteCommitVideo $action): Response + { + $action->handle($commitVideo); + + return response()->noContent(); + } +} diff --git a/app/Http/Controllers/CommitVideoPlaybackController.php b/app/Http/Controllers/CommitVideoPlaybackController.php new file mode 100644 index 0000000000..7f171230c0 --- /dev/null +++ b/app/Http/Controllers/CommitVideoPlaybackController.php @@ -0,0 +1,32 @@ +boolean('poster'); + $path = $commitVideo->path($poster ? 'poster.jpg' : 'video.mp4'); + + // The local disk's temporary URL streams the whole file without byte-range support. + if (config('filesystems.disks.'.config()->string('filesystems.default').'.driver') === 'local') { + return response()->file(Storage::path($path), [ + 'Content-Type' => $poster ? 'image/jpeg' : 'video/mp4', + 'Cache-Control' => 'private, no-store', + 'X-Content-Type-Options' => 'nosniff', + ]); + } + + return redirect()->away(Storage::temporaryUrl($path, now()->addMinutes(5))) + ->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Controllers/CommitVideoProcessingController.php b/app/Http/Controllers/CommitVideoProcessingController.php new file mode 100644 index 0000000000..e946da8d96 --- /dev/null +++ b/app/Http/Controllers/CommitVideoProcessingController.php @@ -0,0 +1,18 @@ +json(['video' => $action->handle($commitVideo)]); + } +} diff --git a/app/Http/Controllers/CommitVideoUploadController.php b/app/Http/Controllers/CommitVideoUploadController.php new file mode 100644 index 0000000000..6667ea5e7f --- /dev/null +++ b/app/Http/Controllers/CommitVideoUploadController.php @@ -0,0 +1,20 @@ +handle($commitVideo, $request->getContent(true)); + + return response()->noContent(); + } +} diff --git a/app/Http/Controllers/ModerationController.php b/app/Http/Controllers/ModerationController.php index b6ca5bf8e1..c85742a369 100644 --- a/app/Http/Controllers/ModerationController.php +++ b/app/Http/Controllers/ModerationController.php @@ -33,7 +33,8 @@ public function show(ShowModerationRequest $request, #[CurrentUser] User $user): 'parent.author', 'linkPreview', 'images', - 'quotedCommit' => fn (BelongsTo $query): BelongsTo => $query->withTrashed()->with(['author', 'linkPreview', 'images'])->withPollFor($user), + 'video', + 'quotedCommit' => fn (BelongsTo $query): BelongsTo => $query->withTrashed()->with(['author', 'linkPreview', 'images', 'video'])->withPollFor($user), ]) ->withStarsFor($user) ->withPollFor($user) diff --git a/app/Http/Requests/CreateCommitReplyRequest.php b/app/Http/Requests/CreateCommitReplyRequest.php index aea37cdf3d..56885fe390 100644 --- a/app/Http/Requests/CreateCommitReplyRequest.php +++ b/app/Http/Requests/CreateCommitReplyRequest.php @@ -59,6 +59,7 @@ public function rules(): array 'reply_recipients' => ['sometimes', 'list', 'max:'.self::MAX_REPLY_RECIPIENTS], 'reply_recipients.*' => ['required', 'string', 'distinct', Rule::in(array_values($parent->mentions ?? []))], 'body' => CreateCommitRequest::bodyRules($this->hasFile('images')), + 'video_id' => ['prohibited'], 'link_preview_url' => ['nullable', 'string', Rule::in(is_string($body) ? resolve(Urls::class)->all($body) : [])], 'images' => ['nullable', 'list', 'max:'.CreateCommitImages::MAX_IMAGES], 'images.*' => [ diff --git a/app/Http/Requests/CreateCommitRequest.php b/app/Http/Requests/CreateCommitRequest.php index 0676ce0dd0..2ccb60ff6f 100644 --- a/app/Http/Requests/CreateCommitRequest.php +++ b/app/Http/Requests/CreateCommitRequest.php @@ -14,6 +14,7 @@ use App\Models\User; use App\Rules\CommitBodyLength; use App\Rules\OrganizationToPostAs; +use App\Rules\ReadyCommitVideo; use App\Rules\VisibleCommit; use App\Services\CommitBodies; use App\Services\Features; @@ -110,8 +111,10 @@ public function rules(): array $attachmentRules['poll'][] = 'prohibits:quoted_commit_id'; return [ - 'body' => self::bodyRules($this->hasFile('images')), + 'body' => self::bodyRules($this->hasFile('images') || $this->filled('video_id')), 'author' => ['nullable', 'string', new OrganizationToPostAs($user)], + 'video_id' => ['bail', 'nullable', 'uuid', 'prohibits:images,poll,quoted_commit_id,parent_id,scheduled_at,author,guild_handle', new ReadyCommitVideo($user)], + 'video_description' => ['nullable', 'string', 'max:1000'], 'quoted_commit_id' => ['nullable', 'uuid', 'prohibits:parent_id', new VisibleCommit($user, 'That commit is no longer available to quote.')], 'link_preview_url' => ['nullable', 'string', Rule::in(is_string($body) ? resolve(Urls::class)->all($body) : [])], ...self::guildRules($this), @@ -194,6 +197,16 @@ public function quotedCommit(): ?Commit : null; } + public function videoId(): ?string + { + return $this->filled('video_id') ? $this->string('video_id')->value() : null; + } + + public function videoDescription(): ?string + { + return $this->filled('video_description') ? $this->string('video_description')->value() : null; + } + public function prepareForValidation(): void { self::normalizeBody($this); diff --git a/app/Http/Requests/CreateCommitVideoProcessingRequest.php b/app/Http/Requests/CreateCommitVideoProcessingRequest.php new file mode 100644 index 0000000000..285100b707 --- /dev/null +++ b/app/Http/Requests/CreateCommitVideoProcessingRequest.php @@ -0,0 +1,44 @@ +route('commitVideo'); + assert($video instanceof CommitVideo); + + return $video->user_id === $this->user()?->id && $video->commit_id === null ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array{} */ + public function rules(): array + { + return []; + } + + /** @return list */ + public function after(): array + { + return [function (Validator $validator): void { + $video = $this->route('commitVideo'); + assert($video instanceof CommitVideo); + + // A wrong size still goes to the job, which rejects it and deletes the stored bytes right away. + if ($video->status === CommitVideoStatus::Uploading && ! Storage::exists($video->path('source'))) { + $validator->errors()->add('video', 'The upload is incomplete. Please choose the video again.'); + } + }]; + } +} diff --git a/app/Http/Requests/CreateCommitVideoRequest.php b/app/Http/Requests/CreateCommitVideoRequest.php new file mode 100644 index 0000000000..0b3303dfe1 --- /dev/null +++ b/app/Http/Requests/CreateCommitVideoRequest.php @@ -0,0 +1,22 @@ +> */ + public function rules(): array + { + return ['size' => ['required', 'integer', 'min:1', 'max:'.CommitVideo::MAX_BYTES]]; + } +} diff --git a/app/Http/Requests/CreateConversationMessageRequest.php b/app/Http/Requests/CreateConversationMessageRequest.php index 9193aa516c..0804e97fbe 100644 --- a/app/Http/Requests/CreateConversationMessageRequest.php +++ b/app/Http/Requests/CreateConversationMessageRequest.php @@ -39,6 +39,7 @@ public static function messageRules(FormRequest $request, ?Conversation $convers return [ 'body' => [$request->hasFile('images') || $request->hasFile('voice') ? 'nullable' : 'required', 'string', 'max:'.Message::MAX_LENGTH], + 'video_id' => ['prohibited'], 'client_id' => ['required', 'uuid'], 'reply_to_id' => ['nullable', 'integer', new RepliableMessage($conversation, $visibleFrom)], 'link_preview_url' => ['nullable', 'string', Rule::in(is_string($body) ? resolve(Urls::class)->all($body) : [])], diff --git a/app/Http/Requests/CreateScheduledCommitRequest.php b/app/Http/Requests/CreateScheduledCommitRequest.php index 0f01ec56a6..2df9af077a 100644 --- a/app/Http/Requests/CreateScheduledCommitRequest.php +++ b/app/Http/Requests/CreateScheduledCommitRequest.php @@ -38,6 +38,7 @@ public function rules(): array return [ 'body' => CreateCommitRequest::bodyRules($this->hasFile('images')), 'author' => ['nullable', 'string', new OrganizationToPostAs($user)], + 'video_id' => ['prohibited'], 'scheduled_at' => ['required', 'date_format:Y-m-d\TH:i:sP', 'after:now', 'before_or_equal:'.now()->addDays(30)->toIso8601String(), new ScheduledCommitLimit($user)], 'parent_id' => ['prohibited'], 'link_preview_url' => ['nullable', 'string', Rule::in(is_string($body) ? resolve(Urls::class)->all($body) : [])], diff --git a/app/Http/Requests/DeleteCommitVideoRequest.php b/app/Http/Requests/DeleteCommitVideoRequest.php new file mode 100644 index 0000000000..2ea7fcfc76 --- /dev/null +++ b/app/Http/Requests/DeleteCommitVideoRequest.php @@ -0,0 +1,26 @@ +route('commitVideo'); + assert($video instanceof CommitVideo); + + return $video->user_id === $this->user()?->id && $video->commit_id === null ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array{} */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Requests/ShowCommitVideoPlaybackRequest.php b/app/Http/Requests/ShowCommitVideoPlaybackRequest.php new file mode 100644 index 0000000000..ace70c6b21 --- /dev/null +++ b/app/Http/Requests/ShowCommitVideoPlaybackRequest.php @@ -0,0 +1,31 @@ +route('commitVideo'); + assert($video instanceof CommitVideo); + $user = $this->user(); + $visible = $video->commit_id === null + ? $video->user_id === $user?->id + : $video->commit !== null && ($video->commit->isVisibleTo($user) || $user?->isAdmin() || $this->hasValidSignature()); + + return $video->status === CommitVideoStatus::Ready && $visible ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array{} */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Requests/ShowCommitVideoRequest.php b/app/Http/Requests/ShowCommitVideoRequest.php new file mode 100644 index 0000000000..e62b166efa --- /dev/null +++ b/app/Http/Requests/ShowCommitVideoRequest.php @@ -0,0 +1,26 @@ +route('commitVideo'); + assert($video instanceof CommitVideo); + + return $video->user_id === $this->user()?->id ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array{} */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Requests/UpdateCommitVideoUploadRequest.php b/app/Http/Requests/UpdateCommitVideoUploadRequest.php new file mode 100644 index 0000000000..d4b12361a5 --- /dev/null +++ b/app/Http/Requests/UpdateCommitVideoUploadRequest.php @@ -0,0 +1,31 @@ +route('commitVideo'); + assert($video instanceof CommitVideo); + + return config('filesystems.disks.'.config()->string('filesystems.default').'.driver') === 'local' + && $video->user_id === $this->user()?->id && $video->status === CommitVideoStatus::Uploading + && $video->created_at->greaterThan(now()->subMinutes(15)) + && (int) $this->header('Content-Length') === $video->size + ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array{} */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Resources/CommitResource.php b/app/Http/Resources/CommitResource.php index 10929956e7..eadfd823cf 100644 --- a/app/Http/Resources/CommitResource.php +++ b/app/Http/Resources/CommitResource.php @@ -7,6 +7,7 @@ use App\Enums\CommitStatus; use App\Models\Commit; use App\Models\CommitImage; +use App\Models\CommitVideo; use App\Models\Guild; use App\Models\Poll; use App\Models\User; @@ -15,6 +16,7 @@ use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Support\Facades\URL; /** * A commit and its author, a user or an organization as its type says, as anyone may see them. @@ -71,6 +73,12 @@ public function toArray(Request $request): array 'stars_count' => $this->whenCounted('stars'), 'replies_count' => $this->whenCounted('replies'), 'link_preview' => $this->whenLoaded('linkPreview'), + 'video' => $this->whenLoaded('video', fn (CommitVideo $video): array => $this->status === CommitStatus::Approved || ! $this->imagesAreVisibleTo($request->user()) + ? $video->toArray() + : [...$video->toArray(), + 'url' => URL::temporarySignedRoute('commit-video-playback.show', now()->addMinutes(5), ['commitVideo' => $video]), + 'poster_url' => URL::temporarySignedRoute('commit-video-playback.show', now()->addMinutes(5), ['commitVideo' => $video, 'poster' => true]), + ]), 'images' => $this->whenLoaded('images', fn (): mixed => $this->status === CommitStatus::Approved || ! $this->imagesAreVisibleTo($request->user()) ? $this->images : $this->images->map(fn (CommitImage $image): array => [...$image->toArray(), 'url' => $image->temporaryUrl()])), diff --git a/app/Jobs/ModerateCommit.php b/app/Jobs/ModerateCommit.php index 97ae6651ba..8b1d7c9d3e 100644 --- a/app/Jobs/ModerateCommit.php +++ b/app/Jobs/ModerateCommit.php @@ -36,7 +36,7 @@ public function __construct(public readonly Commit $commit) */ public function handle(UpdateCommitAiDecision $action, UpdateCommitStatuses $updateCommitStatuses): void { - if ($this->commit->status !== CommitStatus::Pending || $this->commit->trashed()) { + if ($this->commit->status !== CommitStatus::Pending || $this->commit->trashed() || $this->commit->video()->exists()) { return; } diff --git a/app/Jobs/ProcessCommitVideo.php b/app/Jobs/ProcessCommitVideo.php new file mode 100644 index 0000000000..4a6f0b1a30 --- /dev/null +++ b/app/Jobs/ProcessCommitVideo.php @@ -0,0 +1,116 @@ +onQueue('videos'); + } + + /** @return list */ + public function middleware(): array + { + return [new WithoutOverlapping($this->videoId)->releaseAfter(60)->expireAfter(360)]; + } + + public function handle(CommitVideos $videos): void + { + $video = CommitVideo::query()->find($this->videoId); + + if ($video === null || $video->status !== CommitVideoStatus::Processing) { + return; + } + + $directory = storage_path('app/video-processing/'.Str::uuid()); + File::ensureDirectoryExists($directory, 0700); + + try { + throw_if(Storage::size($video->path('source')) !== $video->size || $video->size > CommitVideo::MAX_BYTES, InvalidArgumentException::class, 'Video upload size does not match.'); + + $source = Storage::readStream($video->path('source')); + $target = fopen($directory.'/source', 'wb'); + + throw_if(! is_resource($source) || $target === false, RuntimeException::class, 'Video upload is unavailable.'); + + try { + $bytes = stream_copy_to_stream($source, $target, CommitVideo::MAX_BYTES + 1); + } finally { + fclose($source); + fclose($target); + } + + throw_if($bytes !== $video->size, InvalidArgumentException::class, 'Video upload size does not match.'); + + $metadata = $videos->encode($directory); + + // Cancellation and account deletion may happen while encoding. Only a locked, still-pending row can publish files. + DB::transaction(function () use ($video, $directory, $metadata): void { + $current = CommitVideo::query()->lockForUpdate()->find($video->id); + + if ($current === null || $current->status !== CommitVideoStatus::Processing) { + return; + } + + foreach (['video.mp4', 'poster.jpg'] as $file) { + $stream = fopen($directory.'/'.$file, 'rb'); + assert(is_resource($stream)); + + try { + throw_unless(Storage::put($video->path($file), $stream), RuntimeException::class, 'Video storage failed.'); + } finally { + fclose($stream); + } + } + + $current->update([...$metadata, 'status' => CommitVideoStatus::Ready]); + Storage::delete($video->path('source')); + }); + } catch (InvalidArgumentException) { + $this->failed(); + } catch (Throwable) { + // Decoder output and source metadata never go into failed-job payloads or logs. + throw new RuntimeException('Video processing failed for '.$this->videoId); + } finally { + File::deleteDirectory($directory); + } + } + + public function failed(?Throwable $exception = null): void + { + DB::transaction(function (): void { + $video = CommitVideo::query()->where('status', CommitVideoStatus::Processing)->lockForUpdate()->find($this->videoId); + + if ($video !== null) { + $video->update(['status' => CommitVideoStatus::Failed]); + Storage::deleteDirectory('commit-videos/'.$video->id); + Storage::delete($video->path('source')); + } + }); + } +} diff --git a/app/Jobs/PruneCommitVideos.php b/app/Jobs/PruneCommitVideos.php new file mode 100644 index 0000000000..2269934ae6 --- /dev/null +++ b/app/Jobs/PruneCommitVideos.php @@ -0,0 +1,52 @@ +subDay(); + // Signed upload URLs expire after 15 minutes, so unfinished uploads never need an hour. + $uploadCutoff = now()->subHour(); + + CommitVideo::query()->whereNull('commit_id') + ->where(fn (Builder $query): Builder => $query->where('created_at', '<', $cutoff) + ->orWhere(fn (Builder $query): Builder => $query->whereIn('status', [CommitVideoStatus::Uploading, CommitVideoStatus::Failed])->where('created_at', '<', $uploadCutoff))) + ->eachById($delete->handle(...)); + + // Signed PUTs may arrive after cancellation deleted the row. Files whose row still exists wait for that row's own cleanup. + $orphans = collect(Storage::disk()->listContents('video-uploads')->toArray()) + ->filter(fn (StorageAttributes $entry): bool => $entry->isFile() && Storage::lastModified($entry->path()) < $uploadCutoff->getTimestamp()) + ->map(fn (StorageAttributes $entry): string => $entry->path()); + $kept = CommitVideo::query()->whereKey($orphans->map(fn (string $path): string => basename($path))->filter(fn (string $id): bool => Str::isUuid($id))->values())->pluck('id'); + + Storage::delete($orphans->reject(fn (string $path): bool => $kept->contains(basename($path)))->values()->all()); + + $scratch = storage_path('app/video-processing'); + + if (File::isDirectory($scratch)) { + foreach (glob($scratch.'/*', GLOB_ONLYDIR) ?: [] as $directory) { + if (File::lastModified($directory) < $cutoff->getTimestamp()) { + File::deleteDirectory($directory); + } + } + } + } +} diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 93adc3ffd7..6fa9120bd0 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -62,6 +62,7 @@ * @property-read Collection $quotes * @property-read Collection $images * @property-read Collection $headlines + * @property-read CommitVideo|null $video */ #[Hidden([ 'user', @@ -268,7 +269,14 @@ public function isBeingChecked(): bool { return $this->status === CommitStatus::Pending && $this->ai_decision === null - && $this->created_at->greaterThan(now()->subMinutes(self::CHECKING_MINUTES)); + && $this->created_at->greaterThan(now()->subMinutes(self::CHECKING_MINUTES)) + && $this->video === null; + } + + /** @return HasOne */ + public function video(): HasOne + { + return $this->hasOne(CommitVideo::class); } /** diff --git a/app/Models/CommitVideo.php b/app/Models/CommitVideo.php new file mode 100644 index 0000000000..b146763e61 --- /dev/null +++ b/app/Models/CommitVideo.php @@ -0,0 +1,68 @@ + */ + use HasFactory; + + use HasUuids; + + public const int MAX_BYTES = 100 * 1024 * 1024; + + public const int MAX_SECONDS = 60; + + /** @return array */ + public function casts(): array + { + return ['status' => CommitVideoStatus::class, 'size' => 'integer', 'description' => 'encrypted', 'width' => 'integer', 'height' => 'integer', 'duration' => 'float']; + } + + /** @return BelongsTo */ + public function commit(): BelongsTo + { + return $this->belongsTo(Commit::class); + } + + public function path(string $file): string + { + return $file === 'source' ? 'video-uploads/'.$this->id : 'commit-videos/'.$this->id.'/'.$file; + } + + /** @return array */ + public function toArray(): array + { + return [ + ...parent::toArray(), + 'url' => $this->status === CommitVideoStatus::Ready ? route('commit-video-playback.show', $this) : null, + 'poster_url' => $this->status === CommitVideoStatus::Ready ? route('commit-video-playback.show', [$this, 'poster' => true]) : null, + ]; + } +} diff --git a/app/Queries/CommitBuilder.php b/app/Queries/CommitBuilder.php index 5ebb4ac9da..e570247f89 100644 --- a/app/Queries/CommitBuilder.php +++ b/app/Queries/CommitBuilder.php @@ -226,7 +226,7 @@ public function withQuotedCommitFor(?User $viewer): self 'quotedCommit' => fn (BelongsTo $query): BelongsTo => $query ->withTrashed() ->where(fn (self $query): self => $query->visibleTo($viewer)) - ->with(['author', 'linkPreview' => $this->linkPreviewWithTopicFor($viewer), 'images', 'guild']) + ->with(['author', 'linkPreview' => $this->linkPreviewWithTopicFor($viewer), 'images', 'video', 'guild']) ->withPollFor($viewer), ]); } @@ -256,7 +256,7 @@ public function withPublicPreview(): self return $this ->withVisibleReplyCount(null) ->withCount('stars') - ->with(['author', 'linkPreview', 'images', 'guild', 'parent' => fn (BelongsTo $query): BelongsTo => $query->where('status', CommitStatus::Approved)]); + ->with(['author', 'linkPreview', 'images', 'video', 'guild', 'parent' => fn (BelongsTo $query): BelongsTo => $query->where('status', CommitStatus::Approved)]); } public function pending(): self @@ -269,9 +269,11 @@ public function pending(): self */ public function awaitingModerator(): self { + // Video commits skip the ai check, so they wait for a moderator right away. return $this->pending()->where(fn (self $query): self => $query ->whereNotNull('ai_decision') - ->orWhere('created_at', '<=', now()->subMinutes(Commit::CHECKING_MINUTES))); + ->orWhere('created_at', '<=', now()->subMinutes(Commit::CHECKING_MINUTES)) + ->orWhereHas('video')); } /** @@ -324,7 +326,7 @@ public function withPollFor(?User $viewer): self public function withCardDataFor(?User $viewer): self { return $this - ->with(['author', 'linkPreview' => $this->linkPreviewWithTopicFor($viewer), 'images', 'guild']) + ->with(['author', 'linkPreview' => $this->linkPreviewWithTopicFor($viewer), 'images', 'video', 'guild']) ->withQuotedCommitFor($viewer) ->withStarsFor($viewer) ->withPollFor($viewer) diff --git a/app/Rules/ReadyCommitVideo.php b/app/Rules/ReadyCommitVideo.php new file mode 100644 index 0000000000..a0486d0de5 --- /dev/null +++ b/app/Rules/ReadyCommitVideo.php @@ -0,0 +1,26 @@ +whereKey($value)->where('user_id', $this->user->id)->where('status', CommitVideoStatus::Ready)->whereNull('commit_id')->exists()) { + $fail('Choose a video that has finished uploading and processing.'); + } + } +} diff --git a/app/Services/CommitVideos.php b/app/Services/CommitVideos.php new file mode 100644 index 0000000000..c93cb50ea1 --- /dev/null +++ b/app/Services/CommitVideos.php @@ -0,0 +1,67 @@ +run([ + config()->string('video.ffprobe'), '-v', 'error', '-protocol_whitelist', 'file,pipe', + '-format_whitelist', 'mov,matroska,webm', '-show_streams', '-show_format', '-of', 'json', $directory.'/source', + ]); + + $metadata = json_decode($probe->output(), true); + $metadata = new Fluent(is_array($metadata) ? $metadata : []); + + $stream = $metadata->collect('streams')->firstWhere('codec_type', 'video'); + $stream = new Fluent(is_array($stream) ? $stream : []); + + $duration = $metadata->float('format.duration'); + $width = $stream->integer('width'); + $height = $stream->integer('height'); + + throw_if(! $probe->successful() || $duration <= 0 || $duration > CommitVideo::MAX_SECONDS + || $width < 2 || $height < 2 || $width > 8192 || $height > 8192 || $width * $height > 33554432 + || $stream->integer('disposition.attached_pic') !== 0, InvalidArgumentException::class, 'Choose a playable MP4, MOV or WebM video of up to 60 seconds.'); + + $result = Process::timeout(210)->run([ + config()->string('video.ffmpeg'), '-nostdin', '-v', 'error', '-y', + '-protocol_whitelist', 'file,pipe', '-format_whitelist', 'mov,matroska,webm', '-i', $directory.'/source', + '-map', '0:v:0', '-map', '0:a:0?', '-map_metadata', '-1', '-map_metadata:s', '-1', '-map_chapters', '-1', + '-vf', "scale=w='min(if(gte(iw,ih),1920,1080),iw)':h='min(if(gte(iw,ih),1080,1920),ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1", + '-r', '30', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-pix_fmt', 'yuv420p', + '-maxrate', '8M', '-bufsize', '16M', '-c:a', 'aac', '-b:a', '128k', '-ac', '2', + '-t', '60', '-fs', '70000000', '-movflags', '+faststart', $directory.'/video.mp4', + ]); + + throw_unless($result->successful(), RuntimeException::class, 'Video encoding failed.'); + + $poster = Process::timeout(30)->run([ + config()->string('video.ffmpeg'), '-nostdin', '-v', 'error', '-y', '-i', $directory.'/video.mp4', + '-frames:v', '1', '-map_metadata', '-1', $directory.'/poster.jpg', + ]); + + throw_unless($poster->successful(), RuntimeException::class, 'Video poster creation failed.'); + + $dimensions = getimagesize($directory.'/poster.jpg'); + + throw_if($dimensions === false, RuntimeException::class, 'Video poster is unavailable.'); + + return ['width' => $dimensions[0], 'height' => $dimensions[1], 'duration' => $duration]; + } +} diff --git a/config/video.php b/config/video.php new file mode 100644 index 0000000000..1355ce655f --- /dev/null +++ b/config/video.php @@ -0,0 +1,8 @@ + env('FFMPEG_PATH', 'ffmpeg'), + 'ffprobe' => env('FFPROBE_PATH', 'ffprobe'), +]; diff --git a/database/factories/CommitVideoFactory.php b/database/factories/CommitVideoFactory.php new file mode 100644 index 0000000000..224d5ec78b --- /dev/null +++ b/database/factories/CommitVideoFactory.php @@ -0,0 +1,20 @@ + */ +final class CommitVideoFactory extends Factory +{ + /** @return array */ + public function definition(): array + { + return ['user_id' => User::factory(), 'size' => 1, 'status' => CommitVideoStatus::Uploading]; + } +} diff --git a/database/migrations/2026_10_22_120000_create_commit_videos_table.php b/database/migrations/2026_10_22_120000_create_commit_videos_table.php new file mode 100644 index 0000000000..9992deb65a --- /dev/null +++ b/database/migrations/2026_10_22_120000_create_commit_videos_table.php @@ -0,0 +1,28 @@ +uuid('id')->primary(); + $table->foreignUuid('user_id')->index()->constrained()->cascadeOnDelete(); + $table->foreignUuid('commit_id')->nullable()->unique()->constrained()->cascadeOnDelete(); + $table->string('status')->default(CommitVideoStatus::Uploading->value); + $table->unsignedInteger('size'); + $table->text('description')->nullable(); + $table->unsignedSmallInteger('width')->nullable(); + $table->unsignedSmallInteger('height')->nullable(); + $table->float('duration')->nullable(); + $table->timestamps(); + $table->index(['commit_id', 'created_at']); + }); + } +}; diff --git a/resources/js/components/commit-card.tsx b/resources/js/components/commit-card.tsx index 0f9454e932..f840aa3eba 100644 --- a/resources/js/components/commit-card.tsx +++ b/resources/js/components/commit-card.tsx @@ -20,6 +20,7 @@ import { useThread, } from '@/components/commit-thread'; import { useCommitTranslation } from '@/components/commit-translation'; +import { CommitVideo } from '@/components/commit-video'; import { GraphDimmed, GraphScope, @@ -505,6 +506,9 @@ export function CommitCard({ {translation.notice} {showImages && } + {commit.video && ( + + )} {commit.poll && ( ; + video: ReturnType; linkCard: UseLinkCardReturn; schedule: ReturnType; poll: PollDraft | null; @@ -156,7 +163,10 @@ function CommitComposerBody({ ? characterCount(body) : bodyCharacterCount(body), ); - const isFilled = hasImages || characterCount(body.trim()) >= minBodyLength; + const isFilled = + !!video.file || + hasImages || + characterCount(body.trim()) >= minBodyLength; const error = errors.body ?? errors.link_preview_url ?? errors.author; const scheduleError = errors.scheduled_at ?? @@ -225,7 +235,7 @@ function CommitComposerBody({ return (
{attachments.isDraggingFiles && ( @@ -240,20 +250,27 @@ function CommitComposerBody({ isFilled={isFilled} hasTail={!isInDialog} node={ - - {author === null ? ( - - ) : ( - - )} - + // Videos are only for personal commits, so the switcher steps aside while one is attached. + video.file ? ( + ownNode + ) : ( + + {author === null ? ( + + ) : ( + + )} + + ) } /> @@ -303,7 +320,9 @@ function CommitComposerBody({ value={body} onValueChange={issue.change} onPaste={ - poll === null ? attachments.onPaste : undefined + poll === null && !video.file + ? attachments.onPaste + : undefined } onKeyDown={(event) => preview.handleShortcut(event) || @@ -402,6 +421,15 @@ function CommitComposerBody({ textarea={textareaRef} /> + {!isIssue && ( + + )} + {!preview.isPreviewing && ( + { setTimezone( Intl.DateTimeFormat().resolvedOptions() @@ -662,9 +710,11 @@ export function CommitComposer({ guildHandle ? `guild:${guildHandle}` : 'commit', ); const { body } = stash; + const video = useCommitVideo(); const linkCard = useLinkCard(body); const [draftVersion, setDraftVersion] = useState(0); const drop = () => { + video.remove(); stash.drop(); linkCard.reset(); setDraftVersion((version) => version + 1); @@ -687,6 +737,7 @@ export function CommitComposer({ !guildHandle && !attachments.reading && !hasImages && + !video.file && poll === null && !isScheduling, initialKind: initialIssue, @@ -698,7 +749,11 @@ export function CommitComposer({ const isCommittable = !attachments.reading && - (hasImages || characterCount(body.trim()) >= minBodyLength) && + (!video.file || + (video.ready && !hasImages && !poll && !isScheduling)) && + (video.ready || + hasImages || + characterCount(body.trim()) >= minBodyLength) && (issue.command !== null ? characterCount(body) : bodyCharacterCount(body)) <= maxBodyLength && @@ -773,6 +828,10 @@ export function CommitComposer({ commit_rules_accepted: commitRules.hasAccepted(), human_verification_token: commitRules.humanVerificationToken(), ...(author !== null && { author: author.handle }), + ...(video.ready && { + video_id: video.video!.id, + video_description: video.description, + }), ...(hasImages && { images: attachments.images, image_descriptions: attachments.descriptions, @@ -789,6 +848,7 @@ export function CommitComposer({ return; } + video.attached(); drop(); setAuthor(null); setScheduledAt(''); @@ -816,6 +876,7 @@ export function CommitComposer({ stash={stash} guildHandle={guildHandle} attachments={attachments} + video={video} linkCard={linkCard} schedule={schedule} poll={poll} diff --git a/resources/js/components/commit-thread.tsx b/resources/js/components/commit-thread.tsx index dee57cbc3e..04c222b2f4 100644 --- a/resources/js/components/commit-thread.tsx +++ b/resources/js/components/commit-thread.tsx @@ -41,6 +41,7 @@ import { CommitSecondaryActions } from '@/components/commit-secondary-actions'; import { CommitStarButton } from '@/components/commit-star-button'; import { CommitStatusBadge } from '@/components/commit-status-badge'; import { useCommitTranslation } from '@/components/commit-translation'; +import { CommitVideo } from '@/components/commit-video'; import { ComposerPreviewBody, PreviewToggle, @@ -1668,6 +1669,7 @@ function CommitReply({
{translation.notice} + {reply.video && } {reply.link_preview && reply.link_preview.url !== hiddenLinkPreviewUrl && ( Promise; + disabled: boolean; +}) { + const input = useRef(null); + return ( + <> + { + const selected = event.target.files?.[0]; + event.target.value = ''; + if (selected) void onPick(selected); + }} + /> + + + + + ); +} + +export function CommitVideoPicker({ + attachment, + processing, +}: { + attachment: ReturnType; + processing: boolean; +}) { + const { file, video, ready, error, progress } = attachment; + const id = useId(); + const [describing, setDescribing] = useState(false); + const described = attachment.description.trim() !== ''; + return ( + <> + {file && ( +
+ {ready && video ? ( + + ) : ( +
+ {error ? ( +
+ )} +
+
+

+ {file.name} +

+ {ready && } + {!error && ( + + )} + +
+ {!error && ( + <> + +

+ {ready + ? 'Ready to commit. Your video is not public yet.' + : 'Commit becomes available when your video is ready.'} +

+ + )} + {describing && !error && ( +
+ +