- Improved the upload/edit flow to auto-grab thumbnails.

What changed:
Added shared thumbnail helpers in 
[includes/db.php](/Users/tyemeclifford/Documents/GH/mediaplayer/includes/db.php):YouTube 
direct thumbnails
Dailymotion direct thumbnails
oEmbed thumbnails for Vimeo, Wistia, TikTok, SoundCloud, Spotify, etc.
optional first-frame thumbnail generation for local uploads when ffmpeg 
is installed

Added an “Auto-grab thumbnail” checkbox to 
[admin/add.php](/Users/tyemeclifford/Documents/GH/mediaplayer/admin/add.php) 
and 
[admin/edit.php](/Users/tyemeclifford/Documents/GH/mediaplayer/admin/edit.php).
Reused the new shared downloader in 
[admin/youtube_import.php](/Users/tyemeclifford/Documents/GH/mediaplayer/admin/youtube_import.php).
Documented the behavior in 
[README.md](/Users/tyemeclifford/Documents/GH/mediaplayer/README.md).
This commit is contained in:
Ty Clifford
2026-06-24 13:32:14 -04:00
parent 7ad9c672ca
commit 99492287e7
5 changed files with 264 additions and 24 deletions
+229 -6
View File
@@ -306,6 +306,70 @@ function media_append_query(string $base, array $params): string {
return $base . (strpos($base, '?') === false ? '?' : '&') . $query;
}
function media_http_get(string $url, int $timeout = 12): array {
$url = normalize_media_url($url);
if ($url === '') return ['body' => '', 'code' => 0, 'content_type' => '', 'error' => 'Invalid URL.'];
$headers = [
'User-Agent: Mozilla/5.0 (compatible; TyCliffordMedia/1.0)',
'Accept: image/avif,image/webp,image/png,image/jpeg,image/*;q=0.9,application/json;q=0.8,text/html;q=0.7,*/*;q=0.5',
];
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => true,
]);
$raw = curl_exec($ch);
$err = curl_error($ch);
$code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$header_size = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$content_type = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
if (!is_string($raw) || $raw === '') {
return ['body' => '', 'code' => $code, 'content_type' => $content_type, 'error' => $err ?: 'Empty response.'];
}
return [
'body' => substr($raw, $header_size),
'code' => $code,
'content_type' => $content_type,
'error' => $code >= 400 ? 'HTTP ' . $code : '',
];
}
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", $headers),
'timeout' => $timeout,
'ignore_errors' => true,
],
]);
$body = @file_get_contents($url, false, $context);
$response_headers = $http_response_header ?? [];
$code = 0;
$content_type = '';
foreach ($response_headers as $header) {
if (preg_match('#^HTTP/\S+\s+(\d+)#', $header, $m)) $code = (int)$m[1];
if (stripos($header, 'Content-Type:') === 0) $content_type = trim(substr($header, 13));
}
return [
'body' => is_string($body) ? $body : '',
'code' => $code,
'content_type' => $content_type,
'error' => $code >= 400 ? 'HTTP ' . $code : (!is_string($body) ? 'Unable to fetch URL.' : ''),
];
}
function media_parse_youtube_time(string $value): int {
$value = trim($value);
if ($value === '') return 0;
@@ -334,6 +398,170 @@ function media_twitch_parent_host(): string {
return is_string($host) && $host !== '' ? $host : 'localhost';
}
function media_youtube_id_from_url(string $url): string {
$host = strtolower((string)(parse_url($url, PHP_URL_HOST) ?? ''));
$path = (string)(parse_url($url, PHP_URL_PATH) ?? '');
$segments = media_path_segments($url);
$query = media_query_values($url);
$id = '';
if (media_host_matches($host, 'youtu.be') && isset($segments[0])) $id = $segments[0];
if ($id === '' && isset($query['v'])) $id = media_scalar_string($query['v']);
if ($id === '' && preg_match('#/(?:embed|shorts|live|v)/([^/?#]+)#', $path, $m)) $id = $m[1];
return media_clean_token($id);
}
function media_provider_oembed_endpoint(string $url, string $host): string {
if (media_host_matches($host, 'youtube.com') || media_host_matches($host, 'youtu.be') || media_host_matches($host, 'youtube-nocookie.com')) {
return 'https://www.youtube.com/oembed?format=json&url=' . rawurlencode($url);
}
if (media_host_matches($host, 'vimeo.com')) {
return 'https://vimeo.com/api/oembed.json?url=' . rawurlencode($url);
}
if (media_host_matches($host, 'dailymotion.com') || media_host_matches($host, 'dai.ly')) {
return 'https://www.dailymotion.com/services/oembed?url=' . rawurlencode($url);
}
if (media_host_matches($host, 'tiktok.com')) {
return 'https://www.tiktok.com/oembed?url=' . rawurlencode($url);
}
if (media_host_matches($host, 'soundcloud.com')) {
return 'https://soundcloud.com/oembed?format=json&url=' . rawurlencode($url);
}
if (media_host_matches($host, 'open.spotify.com')) {
return 'https://open.spotify.com/oembed?url=' . rawurlencode($url);
}
if (media_host_matches($host, 'wistia.com') || media_host_matches($host, 'wi.st')) {
return 'https://fast.wistia.com/oembed?url=' . rawurlencode($url);
}
return '';
}
function media_oembed_thumbnail_url(string $url, string $host): string {
$endpoint = media_provider_oembed_endpoint($url, $host);
if ($endpoint === '') return '';
$fetch = media_http_get($endpoint, 8);
if ($fetch['body'] === '' || $fetch['error'] !== '') return '';
$data = json_decode($fetch['body'], true);
if (!is_array($data)) return '';
$thumb = normalize_media_url((string)($data['thumbnail_url'] ?? ''));
return $thumb;
}
function media_provider_thumbnail_url(string $url): string {
$url = normalize_media_url($url);
if ($url === '') return '';
$host = strtolower((string)(parse_url($url, PHP_URL_HOST) ?? ''));
$path = (string)(parse_url($url, PHP_URL_PATH) ?? '');
$segments = media_path_segments($url);
if (media_host_matches($host, 'youtu.be') || media_host_matches($host, 'youtube.com') || media_host_matches($host, 'youtube-nocookie.com')) {
$id = media_youtube_id_from_url($url);
return $id !== '' ? 'https://i.ytimg.com/vi/' . rawurlencode($id) . '/hqdefault.jpg' : '';
}
if (media_host_matches($host, 'dailymotion.com') || media_host_matches($host, 'dai.ly')) {
$id = '';
if (media_host_matches($host, 'dai.ly') && isset($segments[0])) $id = $segments[0];
if ($id === '' && preg_match('#/(?:embed/)?video/([^/?#_]+)#', $path, $m)) $id = $m[1];
$id = media_clean_token($id);
if ($id !== '') return 'https://www.dailymotion.com/thumbnail/video/' . rawurlencode($id);
}
return media_oembed_thumbnail_url($url, $host);
}
function media_thumbnail_extension(string $url, string $content_type): string {
$content_type = strtolower($content_type);
if (str_contains($content_type, 'png')) return 'png';
if (str_contains($content_type, 'webp')) return 'webp';
if (str_contains($content_type, 'gif')) return 'gif';
$ext = media_extension_from_url($url);
return in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true) ? ($ext === 'jpeg' ? 'jpg' : $ext) : 'jpg';
}
function media_download_thumbnail(string $url, string $slug, string $label = 'auto'): string {
$url = normalize_media_url($url);
if ($url === '') return '';
$fetch = media_http_get($url, 12);
if ($fetch['body'] === '' || $fetch['error'] !== '') return '';
if (function_exists('getimagesizefromstring') && !@getimagesizefromstring($fetch['body'])) return '';
$thumb_dir = MEDIA_DIR . 'thumbs/';
if (!is_dir($thumb_dir)) mkdir($thumb_dir, 0755, true);
$label = media_clean_token($label);
if ($label === '') $label = 'auto';
$ext = media_thumbnail_extension($url, (string)$fetch['content_type']);
$fname = $slug . '_' . $label . '_' . time() . '_' . substr(sha1($url), 0, 8) . '.' . $ext;
return file_put_contents($thumb_dir . $fname, $fetch['body']) !== false ? 'thumbs/' . $fname : '';
}
function media_disabled_function(string $name): bool {
$disabled = array_map('trim', explode(',', (string)ini_get('disable_functions')));
return in_array($name, $disabled, true);
}
function media_ffmpeg_path(): string {
$configured = trim((string)getenv('FFMPEG_PATH'));
if ($configured !== '' && is_executable($configured)) return $configured;
if (!function_exists('shell_exec') || media_disabled_function('shell_exec')) return '';
$path = trim((string)@shell_exec('command -v ffmpeg 2>/dev/null'));
return $path !== '' && is_executable($path) ? $path : '';
}
function media_thumbnail_from_local_video(string $file_path, string $slug): string {
$ffmpeg = media_ffmpeg_path();
if ($ffmpeg === '') return '';
$source = MEDIA_DIR . ltrim($file_path, '/');
if ($file_path === '' || !is_file($source) || !is_readable($source)) return '';
$thumb_dir = MEDIA_DIR . 'thumbs/';
if (!is_dir($thumb_dir)) mkdir($thumb_dir, 0755, true);
$fname = $slug . '_frame_' . time() . '_' . substr(sha1($file_path), 0, 8) . '.jpg';
$target = $thumb_dir . $fname;
if (!function_exists('exec') || media_disabled_function('exec')) return '';
$cmd = escapeshellarg($ffmpeg) . ' -y -ss 00:00:01 -i ' . escapeshellarg($source) . ' -frames:v 1 -vf ' . escapeshellarg('scale=1280:-2') . ' ' . escapeshellarg($target) . ' 2>/dev/null';
@exec($cmd, $output, $code);
if ($code === 0 && is_file($target) && filesize($target) > 0 && (!function_exists('getimagesize') || @getimagesize($target))) {
return 'thumbs/' . $fname;
}
if (is_file($target)) unlink($target);
return '';
}
function media_auto_thumbnail_for_video(int $video_id, string $slug): string {
$stmt = get_db()->prepare("SELECT * FROM video_sources WHERE video_id=? ORDER BY sort_order ASC, id ASC");
$stmt->execute([$video_id]);
$sources = $stmt->fetchAll();
foreach ($sources as $source) {
if (!source_is_remote($source)) continue;
$thumb_url = media_provider_thumbnail_url($source['source_url'] ?? '');
$thumbnail = media_download_thumbnail($thumb_url, $slug, 'auto');
if ($thumbnail !== '') return $thumbnail;
}
foreach ($sources as $source) {
if (!source_is_local($source)) continue;
$thumbnail = media_thumbnail_from_local_video($source['file_path'] ?? '', $slug);
if ($thumbnail !== '') return $thumbnail;
}
return '';
}
function media_provider_embed(string $url): ?array {
$parts = @parse_url($url);
if (!is_array($parts) || empty($parts['host'])) return null;
@@ -344,12 +572,7 @@ function media_provider_embed(string $url): ?array {
$query = media_query_values($url);
if (media_host_matches($host, 'youtu.be') || media_host_matches($host, 'youtube.com') || media_host_matches($host, 'youtube-nocookie.com')) {
$id = '';
if (media_host_matches($host, 'youtu.be') && isset($segments[0])) $id = $segments[0];
if ($id === '' && isset($query['v'])) $id = media_scalar_string($query['v']);
if ($id === '' && preg_match('#/(?:embed|shorts|live|v)/([^/?#]+)#', $path, $m)) $id = $m[1];
$id = media_clean_token($id);
$id = media_youtube_id_from_url($url);
if ($id !== '') {
$params = ['rel' => '0', 'modestbranding' => '1', 'playsinline' => '1'];
$start = isset($query['start'])