Admins paste a YouTube link (watch, youtu.be, shorts, live, embed). The link is checked via oEmbed on save and with a "check link" button (not found / not embeddable is rejected, unreachable saves with a warning). Start time can be entered or is taken from the link's timecode; autoplay is optional. The presenter embeds the video via youtube-nocookie.com; participants get the link plus a share button (Web Share API, falls back to copying). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
235 lines
8.0 KiB
PHP
235 lines
8.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service;
|
|
|
|
use Cake\Http\Client;
|
|
use Throwable;
|
|
|
|
/**
|
|
* YouTube helpers for video slides: parses links and timecodes, builds
|
|
* watch/embed URLs and checks via oEmbed whether a video exists and may be embedded.
|
|
*
|
|
* Supported links: youtube.com/watch?v=…, youtu.be/…, /shorts/…, /live/…, /embed/…,
|
|
* youtube-nocookie.com/embed/… (also m. / music. subdomains) and a bare 11 character video id.
|
|
* Timecodes are read from `t` / `start` (query or fragment), e.g. `90`, `90s`, `1m30s`, `1h2m3s`.
|
|
*/
|
|
class YouTubeService
|
|
{
|
|
public const STATUS_OK = 'ok';
|
|
public const STATUS_NOT_FOUND = 'not_found';
|
|
public const STATUS_NOT_EMBEDDABLE = 'not_embeddable';
|
|
public const STATUS_UNREACHABLE = 'unreachable';
|
|
|
|
/**
|
|
* Longest accepted start time (12 hours).
|
|
*/
|
|
public const MAX_START = 43200;
|
|
|
|
public const OEMBED_URL = 'https://www.youtube.com/oembed';
|
|
|
|
protected const ID_PATTERN = '/^[A-Za-z0-9_-]{11}$/';
|
|
|
|
protected const HOSTS = [
|
|
'youtube.com', 'www.youtube.com', 'm.youtube.com', 'music.youtube.com',
|
|
'youtube-nocookie.com', 'www.youtube-nocookie.com', 'youtu.be', 'www.youtu.be',
|
|
];
|
|
|
|
protected Client $client;
|
|
|
|
/**
|
|
* @param \Cake\Http\Client|null $client HTTP client (default: 4 s timeout)
|
|
*/
|
|
public function __construct(?Client $client = null)
|
|
{
|
|
$this->client = $client ?? new Client(['timeout' => 4]);
|
|
}
|
|
|
|
/**
|
|
* Extracts video id and timecode from a YouTube link (or a bare video id).
|
|
*
|
|
* @param string $input Link as entered
|
|
* @return array{videoId: string, start: int|null}|null Null if it is no YouTube video link
|
|
*/
|
|
public static function parseUrl(string $input): ?array
|
|
{
|
|
$input = trim($input);
|
|
if (preg_match(self::ID_PATTERN, $input)) {
|
|
return ['videoId' => $input, 'start' => null];
|
|
}
|
|
if (!preg_match('#^https?://#i', $input)) {
|
|
$input = 'https://' . $input;
|
|
}
|
|
$parts = parse_url($input);
|
|
if ($parts === false) {
|
|
return null;
|
|
}
|
|
$host = strtolower((string)($parts['host'] ?? ''));
|
|
if (!in_array($host, self::HOSTS, true)) {
|
|
return null;
|
|
}
|
|
|
|
parse_str((string)($parts['query'] ?? ''), $query);
|
|
$path = trim((string)($parts['path'] ?? ''), '/');
|
|
$segments = $path === '' ? [] : explode('/', $path);
|
|
|
|
$id = match (true) {
|
|
str_ends_with($host, 'youtu.be') => $segments[0] ?? '',
|
|
($segments[0] ?? '') === 'watch' => is_string($query['v'] ?? null) ? $query['v'] : '',
|
|
in_array($segments[0] ?? '', ['embed', 'shorts', 'live', 'v', 'e'], true) => $segments[1] ?? '',
|
|
default => '',
|
|
};
|
|
if (!preg_match(self::ID_PATTERN, $id)) {
|
|
return null;
|
|
}
|
|
|
|
parse_str((string)($parts['fragment'] ?? ''), $fragment);
|
|
$start = null;
|
|
foreach ([$query['t'] ?? null, $query['start'] ?? null, $fragment['t'] ?? null] as $value) {
|
|
if (is_string($value) && $value !== '') {
|
|
$start = self::parseUrlTime($value);
|
|
if ($start !== null) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
return ['videoId' => $id, 'start' => $start];
|
|
}
|
|
|
|
/**
|
|
* Parses a timecode as used in YouTube links: `90`, `90s`, `1m30s`, `1h2m3s`.
|
|
*
|
|
* @param string $value Timecode
|
|
* @return int|null Seconds, null if invalid
|
|
*/
|
|
public static function parseUrlTime(string $value): ?int
|
|
{
|
|
$value = strtolower(trim($value));
|
|
if (preg_match('/^\d+$/', $value)) {
|
|
return min((int)$value, self::MAX_START);
|
|
}
|
|
if (preg_match('/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/', $value, $m) && $value !== '') {
|
|
return min((int)($m[1] ?? 0) * 3600 + (int)($m[2] ?? 0) * 60 + (int)($m[3] ?? 0), self::MAX_START);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Parses the start time entered in the slide form: `1:30`, `1:02:03`, `2` (= minutes)
|
|
* or the link format `1m30s`.
|
|
*
|
|
* @param string $value Input
|
|
* @return int|null Seconds, null if invalid
|
|
*/
|
|
public static function parseStartInput(string $value): ?int
|
|
{
|
|
$value = str_replace(' ', '', trim($value));
|
|
if (preg_match('/^\d+$/', $value)) {
|
|
return min((int)$value * 60, self::MAX_START);
|
|
}
|
|
if (preg_match('/^(?:(\d+):)?(\d+):([0-5]\d)$/', $value, $m)) {
|
|
return min((int)$m[1] * 3600 + (int)$m[2] * 60 + (int)$m[3], self::MAX_START);
|
|
}
|
|
|
|
return preg_match('/[hms]$/i', $value) ? self::parseUrlTime($value) : null;
|
|
}
|
|
|
|
/**
|
|
* @param int $seconds Seconds
|
|
* @return string `m:ss` or `h:mm:ss`
|
|
*/
|
|
public static function formatTime(int $seconds): string
|
|
{
|
|
$seconds = max(0, $seconds);
|
|
$h = intdiv($seconds, 3600);
|
|
$m = intdiv($seconds % 3600, 60);
|
|
$s = $seconds % 60;
|
|
|
|
return $h > 0 ? sprintf('%d:%02d:%02d', $h, $m, $s) : sprintf('%d:%02d', $m, $s);
|
|
}
|
|
|
|
/**
|
|
* Link to watch the video on YouTube (for participants).
|
|
*
|
|
* @param string $videoId Video id
|
|
* @param int $start Start in seconds
|
|
* @return string
|
|
*/
|
|
public static function watchUrl(string $videoId, int $start = 0): string
|
|
{
|
|
$query = ['v' => $videoId] + ($start > 0 ? ['t' => $start . 's'] : []);
|
|
|
|
return 'https://www.youtube.com/watch?' . http_build_query($query);
|
|
}
|
|
|
|
/**
|
|
* Player URL for the iframe on the presenter screen (privacy-enhanced mode).
|
|
*
|
|
* @param string $videoId Video id
|
|
* @param int $start Start in seconds
|
|
* @param bool $autoplay Start playing when the slide is shown
|
|
* @return string
|
|
*/
|
|
public static function embedUrl(string $videoId, int $start = 0, bool $autoplay = false): string
|
|
{
|
|
$query = ['rel' => 0, 'playsinline' => 1]
|
|
+ ($start > 0 ? ['start' => $start] : [])
|
|
+ ($autoplay ? ['autoplay' => 1] : []);
|
|
|
|
return 'https://www.youtube-nocookie.com/embed/' . rawurlencode($videoId) . '?' . http_build_query($query);
|
|
}
|
|
|
|
/**
|
|
* Asks YouTube (oEmbed) whether the video exists and may be embedded.
|
|
*
|
|
* @param string $videoId Video id
|
|
* @return array{status: string, title: string|null} status: one of the STATUS_* constants
|
|
*/
|
|
public function check(string $videoId): array
|
|
{
|
|
try {
|
|
$response = $this->client->get(self::OEMBED_URL, [
|
|
'url' => self::watchUrl($videoId),
|
|
'format' => 'json',
|
|
]);
|
|
} catch (Throwable) {
|
|
return ['status' => self::STATUS_UNREACHABLE, 'title' => null];
|
|
}
|
|
|
|
$code = $response->getStatusCode();
|
|
if ($code === 200) {
|
|
$data = $response->getJson();
|
|
$title = is_array($data) && is_string($data['title'] ?? null) ? trim($data['title']) : null;
|
|
|
|
return ['status' => self::STATUS_OK, 'title' => $title !== '' ? $title : null];
|
|
}
|
|
|
|
return [
|
|
'status' => match (true) {
|
|
in_array($code, [401, 403], true) => self::STATUS_NOT_EMBEDDABLE,
|
|
in_array($code, [400, 404], true) => self::STATUS_NOT_FOUND,
|
|
default => self::STATUS_UNREACHABLE,
|
|
},
|
|
'title' => null,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* German message for a check status.
|
|
*
|
|
* @param string $status STATUS_* constant
|
|
* @return string
|
|
*/
|
|
public static function statusMessage(string $status): string
|
|
{
|
|
return match ($status) {
|
|
self::STATUS_OK => __('Das Video ist verfügbar und kann eingebettet werden.'),
|
|
self::STATUS_NOT_FOUND => __('Dieses Video gibt es nicht (mehr) oder es ist privat.'),
|
|
self::STATUS_NOT_EMBEDDABLE => __('Dieses Video darf nicht eingebettet werden (vom Kanal gesperrt). Bitte wähle ein anderes Video.'),
|
|
default => __('YouTube war gerade nicht erreichbar, das Video konnte nicht geprüft werden.'),
|
|
};
|
|
}
|
|
}
|