Files
laravel-video-extractor/src/Strategies/Vk/AlVideoStrategy.php
2026-07-16 21:56:58 +03:00

183 lines
6.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Apoloz\VideoExtractor\Strategies\Vk;
use Apoloz\VideoExtractor\Dto\FormatDto;
use Apoloz\VideoExtractor\Dto\ThumbnailDto;
use Apoloz\VideoExtractor\Dto\VideoInfoDto;
use Apoloz\VideoExtractor\Dto\VideoRef;
use Apoloz\VideoExtractor\Exceptions\LoginRequiredException;
use Apoloz\VideoExtractor\Exceptions\VideoNotFoundException;
use Apoloz\VideoExtractor\Http\HttpClient;
use Apoloz\VideoExtractor\Platform\Platform;
use Apoloz\VideoExtractor\Strategies\StrategyInterface;
/**
* Extracts VK videos via the same POST endpoint yt-dlp uses.
*
* POST https://vk.com/al_video.php (act=show, al=1, video={oid}_{id})
*
* The response is JSON (`charset=windows-1251`) shaped as
* `{"payload": [code, [title, html, js, html, opts]]}` where `opts` (index 4)
* holds `mvData` (metadata) and `player.params[0]` (thumbnail `jpg`, formats).
*
* This is the fallback strategy: it yields a single thumbnail URL rather than
* the multi-resolution `image[]` returned by {@see VideoExtStrategy}, but it
* matches yt-dlp's proven primary method and surfaces explicit error codes.
*/
final class AlVideoStrategy implements StrategyInterface
{
use InteractsWithVkPayload;
private const ENDPOINT = 'https://vk.com/al_video.php';
/** @var array<string, int> map of `url<height>` params to heights */
private const URL_HEIGHTS = [
'url144' => 144,
'url240' => 240,
'url360' => 360,
'url480' => 480,
'url720' => 720,
'url1080' => 1080,
'url1440' => 1440,
'url2160' => 2160,
];
public function __construct(
private readonly HttpClient $http,
) {}
public function extract(VideoRef $ref): VideoInfoDto
{
$data = $this->fetchParams($ref);
$mvData = is_array($data['_mvData'] ?? null) ? $data['_mvData'] : [];
return new VideoInfoDto(
platform: Platform::VK,
id: $ref->id,
title: self::str($mvData, 'title') ?? self::str($data, 'md_title'),
description: self::str($mvData, 'desc') ?? self::str($data, 'description'),
duration: self::int($mvData, 'duration') ?? self::int($data, 'duration'),
uploader: self::str($data, 'md_author'),
uploaderId: self::str($data, 'author_id'),
timestamp: self::int($data, 'date'),
viewCount: null,
likeCount: self::int($mvData, 'likes'),
commentCount: self::int($mvData, 'commcount'),
isLive: self::int($data, 'live') === 2,
thumbnails: $this->extractThumbnails($data),
formats: $this->extractFormats($data),
categories: [],
formatExpiresAt: null,
);
}
public function extractThumbnail(VideoRef $ref): ?string
{
return self::str($this->fetchParams($ref), 'jpg');
}
/**
* Perform the POST and return the resolved `player.params[0]` array,
* alongside the `mvData` metadata under the `_mvData` key.
*
* @return array<string|int, mixed>
*
* @throws LoginRequiredException payload code 3
* @throws VideoNotFoundException payload code 8
*/
private function fetchParams(VideoRef $ref): array
{
$response = $this->http->post(self::ENDPOINT, [
'act' => 'show',
'al' => 1,
'video' => $ref->id,
...($ref->query !== [] ? ['list' => $ref->query['list'] ?? null] : []),
], [
'Referer' => 'https://vk.com/',
'X-Requested-With' => 'XMLHttpRequest',
]);
$payload = json_decode($this->http->bodyUtf8($response, 'Windows-1251'), true);
if (!is_array($payload) || !isset($payload['payload']) || !is_array($payload['payload'])) {
throw new VideoNotFoundException("Unexpected VK al_video response for {$ref->id}");
}
[$code, $body] = $payload['payload'];
$code = (int) $code;
if ($code === 3) {
throw new LoginRequiredException("VK video requires login: {$ref->id}");
}
if ($code === 8) {
// payload body[0] holds the raw quoted message, e.g.
// "\"Video has been deleted.\"" -> trim the surrounding quotes.
$message = isset($body[0]) && is_string($body[0]) ? trim($body[0], '"') : '';
throw new VideoNotFoundException(
$message !== '' ? "VK video unavailable: {$message}" : "VK video unavailable: {$ref->id}",
);
}
$opts = is_array($body) && isset($body[4]) && is_array($body[4]) ? $body[4] : [];
$player = is_array($opts['player'] ?? null) ? $opts['player'] : [];
$params = is_array($player['params'] ?? null) ? $player['params'] : [];
$params0 = is_array($params[0] ?? null) ? $params[0] : [];
// Attach mvData for the caller without polluting the params namespace.
$params0['_mvData'] = is_array($opts['mvData'] ?? null) ? $opts['mvData'] : [];
return $params0;
}
/**
* @param array<string|int, mixed> $data
* @return ThumbnailDto[]
*/
private function extractThumbnails(array $data): array
{
$jpg = self::str($data, 'jpg');
if ($jpg === null) {
return [];
}
return [new ThumbnailDto($jpg)];
}
/**
* @param array<string|int, mixed> $data
* @return FormatDto[]
*/
private function extractFormats(array $data): array
{
$formats = [];
foreach (self::URL_HEIGHTS as $key => $height) {
$url = self::str($data, $key);
if ($url !== null) {
$formats[] = new FormatDto(
url: $url,
formatId: $key,
ext: 'mp4',
height: $height,
expiresAt: self::parseExpiresSeconds($url),
);
}
}
$hls = self::str($data, 'hls');
if ($hls !== null) {
$formats[] = new FormatDto($hls, 'hls', 'mp4', null, self::parseExpiresSeconds($hls));
}
$dash = self::str($data, 'dash_sep');
if ($dash !== null) {
$formats[] = new FormatDto($dash, 'dash_sep', 'mp4', null, self::parseExpiresSeconds($dash));
}
return $formats;
}
}