Skip to content

A self-hosted media server and file management system

refactor: split transition controller into smaller functions

aminnausin80fbf5933f75
diff --git a/app/Exceptions/TranscriptionException.php b/app/Exceptions/TranscriptionException.php
new file mode 100644
index 00000000..6d41e901
--- /dev/null
+++ b/app/Exceptions/TranscriptionException.php
@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Exceptions;
+
+class TranscriptionException extends \RuntimeException {
+ public function __construct(
+ string $message,
+ private readonly int $status,
+ private readonly ?string $error = null,
+ ) {
+ parent::__construct($message);
+ }
+
+ public function status(): int {
+ return $this->status;
+ }
+
+ public function error(): ?string {
+ return $this->error;
+ }
+}
diff --git a/app/Http/Controllers/Api/V1/Metadata/TranscriptController.php b/app/Http/Controllers/Api/V1/Metadata/TranscriptController.php
index 875a577a..1602f0eb 100644
--- a/app/Http/Controllers/Api/V1/Metadata/TranscriptController.php
+++ b/app/Http/Controllers/Api/V1/Metadata/TranscriptController.php
@@ -3,12 +3,13 @@
namespace App\Http\Controllers\Api\V1\Metadata;
use App\Data\Access\RateLimitData;
+use App\Exceptions\TranscriptionException;
use App\Http\Controllers\Controller;
use App\Http\Resources\SubtitleResource;
-use App\Jobs\VerifyFiles;
use App\Models\Metadata;
+use App\Models\Subtitle;
use App\Services\RateLimitService;
-use Illuminate\Http\Client\ConnectionException;
+use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
@@ -20,52 +21,84 @@ class TranscriptController extends Controller {
public function regenerate(Metadata $metadata): JsonResponse {
$limits = $this->getRateLimits();
-
$isAdmin = Gate::allows('admin');
- $rateLimitError = ! $isAdmin ? $this->rateLimiter->getRateLimitError($limits) : null;
- if ($rateLimitError) {
- return $rateLimitError;
- }
-
if (! $isAdmin) {
- $this->rateLimiter->hitRateLimits($limits);
- }
+ $rateLimitError = $this->rateLimiter->getRateLimitError($limits);
- $videoPath = VerifyFiles::getAbsoluteMediaPath($metadata->video);
- $media = $metadata->video;
- $videoPath = str_starts_with($media->path, 'storage/')
- ? substr($media->path, 8)
- : $media->path;
+ if ($rateLimitError) {
+ return $rateLimitError;
+ }
- if (! $videoPath || ! Storage::disk('public')->exists($videoPath)) {
- return response()->json(['message' => Storage::disk('public')->path(''), 'p' => $videoPath], 404);
+ $this->rateLimiter->hitRateLimits($limits);
}
- $absolutePath = Storage::disk('public')->path($videoPath);
-
try {
- $response = Http::timeout(120)->attach('file', fopen($absolutePath, 'r'), basename($absolutePath))->post(config('services.transcribe.url'));
- } catch (ConnectionException $e) {
+ $transcript = $this->generateTranscript($metadata);
+ $subtitle = $this->saveTranscript($metadata, $transcript['vtt'], $transcript['language']);
+
return response()->json([
- 'message' => 'Transcription service is unavailable.',
- ], 503);
+ 'message' => 'Transcript generated successfully.',
+ 'subtitle' => new SubtitleResource($subtitle),
+ 'language' => $transcript['language'],
+ 'language_probability' => $transcript['language_probability'],
+ 'segment_count' => $transcript['segment_count'],
+ ]);
+ } catch (FileNotFoundException $e) {
+ return response()->json(['message' => $e->getMessage()], 404);
+ } catch (TranscriptionException $e) {
+ return response()->json(['message' => $e->getMessage(), 'error' => $e->error()], $e->status());
}
+ }
+
+ private function getRateLimits(): array {
+ $userId = Auth::id();
+
+ return [
+ new RateLimitData(
+ key: "transcript-regenerate:minute:{$userId}",
+ maxAttempts: 1,
+ decaySeconds: 60,
+ message: 'Too many requests.',
+ ),
+ new RateLimitData(
+ key: "transcript-regenerate:hour:{$userId}",
+ maxAttempts: 10,
+ decaySeconds: 3600,
+ message: 'Hourly limit reached.',
+ ),
+ ];
+ }
+
+ private function generateTranscript(Metadata $metadata): array {
+ $absolutePath = $this->getVideoPath($metadata);
+ $response = Http::timeout(120)->attach('file', fopen($absolutePath, 'r'), basename($absolutePath))->post(config('services.transcribe.url'));
if ($response->failed()) {
- return response()->json([
- 'message' => 'Transcription failed.',
- 'error' => $response->json('detail') ?? $response->body(),
- ], $response->status());
+ throw new TranscriptionException('Transcription failed.', $response->status(), $response->json('detail') ?? $response->body());
}
- $vtt = $response->json('vtt');
- $language = $response->json('language');
+ if (! $response->json('vtt')) {
+ throw new TranscriptionException('Transcription service returned an invalid response.', 502);
+ }
+
+ return $response->json();
+ }
- if (! $vtt) {
- return response()->json(['message' => 'Transcription service returned an invalid response.'], 502);
+ private function getVideoPath(Metadata $metadata): string {
+ $media = $metadata->video;
+ $videoPath = str_starts_with($media->path, 'storage/')
+ ? substr($media->path, 8)
+ : $media->path;
+
+ if (! $videoPath || ! Storage::disk('public')->exists($videoPath)) {
+ throw new FileNotFoundException('File not found for ' . $metadata->composite_id);
}
+ return Storage::disk('public')->path($videoPath);
+ }
+
+ private function saveTranscript(Metadata $metadata, string $vtt, ?string $language): Subtitle {
$subtitle = $metadata->subtitles()->firstOrNew([
'source_key' => 'generated',
'track_id' => -1,
@@ -80,10 +113,9 @@ class TranscriptController extends Controller {
'format' => 'vtt',
'is_default' => ! $metadata->subtitles()->exists(),
'is_forced' => false,
+ 'source_key' => 'generated',
]);
- $subtitle->source_key = 'generated';
-
$path = $subtitle->getFilePath('vtt', $language);
$subtitle->path = $path;
$subtitle->save();
@@ -94,31 +126,6 @@ class TranscriptController extends Controller {
Storage::disk('local')->delete($oldPath);
}
- return response()->json([
- 'message' => 'Transcript generated successfully.',
- 'subtitle' => new SubtitleResource($subtitle),
- 'language' => $language,
- 'language_probability' => $response->json('language_probability'),
- 'segment_count' => $response->json('segment_count'),
- ]);
- }
-
- private function getRateLimits(): array {
- $userId = Auth::id();
-
- return [
- new RateLimitData(
- key: "transcript-regenerate:minute:{$userId}",
- maxAttempts: 1,
- decaySeconds: 60,
- message: 'Too many requests.',
- ),
- new RateLimitData(
- key: "transcript-regenerate:hour:{$userId}",
- maxAttempts: 10,
- decaySeconds: 3600,
- message: 'Hourly limit reached.',
- ),
- ];
+ return $subtitle;
}
}
diff --git a/app/Models/Subtitle.php b/app/Models/Subtitle.php
index b3363ffc..e468fed8 100644
--- a/app/Models/Subtitle.php
+++ b/app/Models/Subtitle.php
@@ -40,6 +40,7 @@ class Subtitle extends Model {
'path',
'is_default',
'is_forced',
+ 'source_key',
];
public function metadata(): BelongsTo {