Laravel 應用程式如何透過佇列工作處理影片及 Podcast 連結
Handling video and podcast links in a Laravel app with queued jobs
Laravel 應用程式可透過 Importly 處理 YouTube、TikTok 或 Podcast 連結,取得逐字稿、檔案下載連結或影片詳情。文章以佇列工作分開啟動匯入及檢查狀態,每 20 秒重試檢查,避免長時間佔用工作程序或重複啟動任務。 transcript 支援使用字幕,沒有字幕時則改用語音轉文字。
A lot of Laravel apps end up with the same feature: a user pastes a YouTube, TikTok or podcast link, and the app needs the transcript or the file. It usually works on your machine. Then it runs on a server and the media job is the one that breaks: sites block datacenter IPs, and plenty of videos have no captions to read.
I built Importly for this, so that's what this post calls. You send it a link and get back the transcript, a download link for the file, or the video's details, and it works from servers. The part worth getting right in Laravel is the queue side, so that's most of this post.
Long imports can take a few minutes, so don't hold a worker for them. One job starts the Importly job and stores its ID, and a second job checks the status and dispatches itself again 20 seconds later until it's done. A retry only ever re-runs the check, so it never starts the job twice.
Key and config
Put the key in .env and read it through config/services.php, so it still works after php artisan config:cache:
// config/services.php
'importly' => [
'key' => env('IMPORTLY_API_KEY'),
],
The jobs save to a Video model with url, importly_job_id, importly_status, importly_result (json, cast to array) and importly_error columns.
A small client
A 429 or 5xx can work later, so the client throws with a retryAfter. A bad link, a wrong key or a low balance won't change on a retry, so those throw with retryAfter set to null and the job fails.
// app/Exceptions/ImportlyException.php
class ImportlyException extends RuntimeException
{
public function __construct(string $message, public readonly ?int $retryAfter = null)
{
parent::__construct($message);
}
}
// app/Services/Importly.php
class Importly
{
public static function post(string $path, array $body): array
{
return self::data(self::client()->post($path, $body));
}
public static function get(string $path, array $query): array
{
return self::data(self::client()->get($path, $query));
}
private static function client()
{
return Http::baseUrl('https://api.importly.io')
->withToken(config('services.importly.key'))
->acceptJson()
->timeout(70); // longer than the 30-second wait on /transcribe
}
private static function data(Response $response): array
{
$json = $response->json() ?? [];
if ($response->successful() && ($json['success'] ?? false)) {
return $json['data'];
}
$message = sprintf('Importly %d %s: %s', $response->status(), $json['code'] ?? '', $json['error'] ?? 'request failed');
$retryAfter = match (true) {
$response->status() === 429 => (int) ($json['retryAfter'] ?? 60),
$response->serverError() => 30,
default => null, // a retry won't change it
};
throw new ImportlyException($message, $retryAfter);
}
}
The jobs
A shared trait waits for retryAfter on a 429 or 5xx, up to 5 tries, fails straight away on anything else, and saves the outcome:
// app/Jobs/Concerns/TracksImportlyJob.php
trait TracksImportlyJob
{
public int $tries = 5;
protected function retryOrFail(ImportlyException $error): void
{
$error->retryAfter === null ? $this->fail($error) : $this->release($error->retryAfter);
}
protected function finishOrCheck(Video $video, string $kind, array $job): void
{
$video->update(['importly_job_id' => $job['jobId'], 'importly_status' => $job['status']]);
if (in_array($job['status'], ['queued', 'running'], true)) {
CheckImportlyJob::dispatch($video->id, $kind, $job['jobId'])->delay(now()->addSeconds(20));
} else {
$this->saveResult($video, $job);
}
}
protected function saveResult(Video $video, array $job): void
{
if ($job['status'] === 'completed') {
$video->update(['importly_status' => 'completed', 'importly_result' => $job['result']]);
} else {
$video->update(['importly_status' => 'failed', 'importly_error' => "{$job['code']}: {$job['message']}"]);
}
}
}
mode: auto uses the video's captions and falls back to speech-to-text when it has none. wait: true holds the request for up to 30 seconds, so a captioned video usually comes back from the first call. maxCostDollars stops a long video before it's charged more than you want.
// app/Jobs/TranscribeLink.php
class TranscribeLink implements ShouldQueue
{
use Queueable, TracksImportlyJob;
public function __construct(public int $videoId) {}
public function handle(): void
{
$video = Video::findOrFail($this->videoId);
try {
$job = Importly::post('/transcribe', [
'url' => $video->url,
'mode' => 'auto',
'wait' => true,
'maxCostDollars' => 1,
]);
} catch (ImportlyException $error) {
$this->retryOrFail($error);
return;
}
$this->finishOrCheck($video, 'transcribe', $job);
}
}
Anything still queued or running goes to the check job, which gives up after an hour:
// app/Jobs/CheckImportlyJob.php
class CheckImportlyJob implements ShouldQueue
{
use Queueable, TracksImportlyJob;
public function __construct(public int $videoId, public string $kind, public string $jobId, public int $checks = 1) {}
public function handle(): void
{
$video = Video::findOrFail($this->videoId);
try {
$job = Importly::get("/{$this->kind}/status", ['id' => $this->jobId]);
} catch (ImportlyException $error) {
$this->retryOrFail($error);
return;
}
$pending = in_array($job['status'], ['queued', 'running'], true);
if ($pending && $this->checks < 180) {
self::dispatch($this->videoId, $this->kind, $this->jobId, $this->checks + 1)->delay(now()->addSeconds(20));
} elseif ($pending) {
$video->update(['importly_status' => 'failed', 'importly_error' => "still {$job['status']} after an hour"]);
} else {
$this->saveResult($video, $job);
}
}
}
Dispatch it once the record is saved, and run php artisan queue:work (or Horizon). The sync driver runs the 20-second checks back to back, so use a real queue driver outside tests.
$video = Video::create($request->validate(['url' => 'required|url']));
TranscribeLink::dispatch($video->id);
A finished transcript's importly_result has text plus segments with start and end times. Downloading the file instead is the same pattern with POST /import, which returns a link to the file.
Webhooks and the rest
If you'd rather not poll, Importly can call a webhook when the job finishes. Keep the check job as a fallback, since each job gets one delivery. The full guide has the signed webhook controller in PHP (raw body, timestamp tolerance, secret rotation), the CSRF exception, the import job and the rate limits worth knowing before you queue hundreds of links:
It's free to try, no card required.
來源:DEV Community · dev.to