latest update

This commit is contained in:
ghassan committed 2026-04-05 03:30:22 +03:00
1 parent 64eadfaf56
commit 2a562b99f1
25 files changed
+2617 -2337

No files matched your search

+9 -4
View File
@@ -33,6 +33,8 @@ class CommentController extends Controller
'body' => $request->body,
'parent_id' => $request->parent_id,
]);
// $video->increment('comment_count'); // Disabled - was causing SQL error
$comment->load('user:id,name,avatar_url');
// Handle mentions
preg_match_all('/@(\w+)/', $request->body, $matches);
@@ -41,9 +43,10 @@ class CommentController extends Controller
// For now, we just parse them
}
$video->increment('comment_count');
return response()->json(['success' => true, 'comment' => $comment->load('user')]);
return response()->json([
'success' => true,
'comment' => $comment->load('user:id,name,avatar_url'),
]);
}
public function update(Request $request, Comment $comment)
@@ -60,7 +63,9 @@ class CommentController extends Controller
'body' => $request->body,
]);
return response()->json($comment->load('user'));
$comment->load('user:id,name,avatar_url');
return response()->json($comment->load('user:id,name,avatar_url'));
}
public function destroy(Comment $comment)
+143 -130
View File
@@ -18,12 +18,35 @@ class VideoController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['index', 'show', 'search', 'stream', 'trending', 'shorts']);
$this->middleware('auth')->except(['index', 'show', 'search', 'stream', 'hls', 'trending', 'shorts']);
}
public function index()
{
$videos = Video::public()->latest()->get();
$filter = request('filter', 'all');
$query = Video::public();
if ($filter !== 'all') {
switch ($filter) {
case 'latest':
$query->latest();
break;
case 'music':
$query->where('type', 'music');
break;
case 'match':
$query->where('type', 'match');
break;
default:
$query->where('title', 'LIKE', '%'.$filter.'%')
->orWhere('description', 'LIKE', '%'.$filter.'%');
}
} else {
$query->latest();
}
$videos = $query->limit(50)->get();
return view('videos.index', compact('videos'));
}
@@ -76,7 +99,6 @@ class VideoController extends Controller
$thumbFilename = Str::uuid().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$thumbnailPath = $request->file('thumbnail')->storeAs('public/thumbnails', $thumbFilename);
} else {
// Extract thumbnail from video using FFmpeg
try {
$ffmpeg = FFMpeg::create();
$videoPath = storage_path('app/'.$path);
@@ -88,7 +110,6 @@ class VideoController extends Controller
$thumbFilename = Str::uuid().'.jpg';
$thumbFullPath = storage_path('app/public/thumbnails/'.$thumbFilename);
// Ensure thumbnails directory exists
if (! file_exists(storage_path('app/public/thumbnails'))) {
mkdir(storage_path('app/public/thumbnails'), 0755, true);
}
@@ -97,12 +118,10 @@ class VideoController extends Controller
$thumbnailPath = 'public/thumbnails/'.$thumbFilename;
}
} catch (\Exception $e) {
// Log the error but don't fail the upload
\Log::error('FFmpeg failed to extract thumbnail: '.$e->getMessage());
\Log::error('FFmpeg thumbnail error: '.$e->getMessage());
}
}
// Get video dimensions and detect orientation using FFmpeg
$width = null;
$height = null;
$orientation = 'landscape';
@@ -119,22 +138,15 @@ class VideoController extends Controller
$width = $videoStream->get('width');
$height = $videoStream->get('height');
// Auto-detect orientation based on dimensions
if ($width && $height) {
if ($height > $width) {
$orientation = 'portrait';
} elseif ($width > $height) {
$orientation = 'landscape';
} else {
$orientation = 'square';
}
if ($height > $width) $orientation = 'portrait';
elseif ($width > $height) $orientation = 'landscape';
else $orientation = 'square';
}
}
}
} catch (\Exception $e) {
// Log the error but don't fail the upload
\Log::error('FFprobe failed to get video dimensions: '.$e->getMessage());
// Use default orientation
\Log::error('FFprobe error: '.$e->getMessage());
}
$video = Video::create([
@@ -154,18 +166,16 @@ class VideoController extends Controller
'type' => $request->type ?? 'generic',
]);
// Dispatch compression job in the background
CompressVideoJob::dispatch($video);
CompressVideoJob::dispatch($video)
->onQueue('video-processing')
->onConnection('database');
// Load user relationship for email
$video->load('user');
// Send email notification
try {
Mail::to(Auth::user()->email)->send(new VideoUploaded($video, Auth::user()->name));
} catch (\Exception $e) {
// Log the error but don't fail the upload
\Log::error('Email notification failed: '.$e->getMessage());
\Log::error('Email error: '.$e->getMessage());
}
return response()->json([
@@ -176,15 +186,12 @@ class VideoController extends Controller
public function show(Request $request, Video $video)
{
// Check if user can view this video
if (! $video->canView(Auth::user())) {
abort(404, 'Video not found');
}
// Track view if user is logged in
if (Auth::check()) {
$user = Auth::user();
// Add view if not already viewed recently (within last hour)
$existingView = \DB::table('video_views')
->where('user_id', $user->id)
->where('video_id', $video->id)
@@ -200,10 +207,8 @@ class VideoController extends Controller
}
}
// Load comments with user relationship
$video->load(['comments.user', 'comments.replies.user', 'matchRounds.points', 'coachReviews']);
// Handle playlist navigation if playlist parameter is provided
$playlist = null;
$nextVideo = null;
$previousVideo = null;
@@ -219,14 +224,12 @@ class VideoController extends Controller
}
}
// Get recommended videos (exclude current video)
$recommendedVideos = Video::public()
->where('id', '!=', $video->id)
->latest()
->limit(20)
->get();
// Render the appropriate view based on video type
$view = match ($video->type) {
'match' => 'videos.types.match',
'music' => 'videos.types.music',
@@ -251,17 +254,14 @@ class VideoController extends Controller
public function edit(Video $video, Request $request)
{
// Check if user owns the video
if (Auth::id() !== $video->user_id) {
abort(403, 'You do not have permission to edit this video.');
abort(403);
}
// If not AJAX request, redirect to show page with edit parameter
if (! $request->expectsJson() && ! $request->ajax()) {
return redirect()->route('videos.show', $video->id)->with('openEditModal', true);
}
// For AJAX request, return JSON
return response()->json([
'success' => true,
'video' => [
@@ -278,9 +278,8 @@ class VideoController extends Controller
public function update(Request $request, Video $video)
{
// Check if user owns the video
if (Auth::id() !== $video->user_id) {
abort(403, 'You do not have permission to edit this video.');
abort(403);
}
$request->validate([
@@ -302,14 +301,12 @@ class VideoController extends Controller
$data['thumbnail'] = basename($data['thumbnail']);
}
// Set default visibility if not provided
if (! isset($data['visibility'])) {
unset($data['visibility']);
}
$video->update($data);
// Return JSON for AJAX requests
if ($request->expectsJson() || $request->ajax()) {
return response()->json([
'success' => true,
@@ -328,20 +325,16 @@ class VideoController extends Controller
public function destroy(Request $request, Video $video)
{
// Check if user owns the video
if (Auth::id() !== $video->user_id) {
abort(403, 'You do not have permission to delete this video.');
abort(403);
}
$videoTitle = $video->title;
Storage::delete('public/videos/'.$video->filename);
if ($video->thumbnail) {
Storage::delete('public/thumbnails/'.$video->thumbnail);
}
$video->delete();
// Return JSON for AJAX requests
if ($request->expectsJson() || $request->ajax()) {
return response()->json([
'success' => true,
@@ -352,9 +345,73 @@ class VideoController extends Controller
return redirect()->route('videos.index')->with('success', 'Video deleted!');
}
public function trending(Request $request)
{
$hours = $request->get('hours', 48);
$limit = $request->get('limit', 50);
$hours = min(max($hours, 24), 168);
$limit = min(max($limit, 10), 100);
$videos = Video::public()
->where('status', 'ready')
->where('created_at', '>=', now()->subDays(10))
->with('user')
->get();
$videos = $videos->map(function ($video) use ($hours) {
$recentViews = \DB::table('video_views')
->where('video_id', $video->id)
->where('watched_at', '>=', now()->subHours($hours))
->count();
$likeCount = \DB::table('video_likes')
->where('video_id', $video->id)
->count();
$ageHours = $video->created_at->diffInHours(now());
$velocity = $recentViews / $hours;
$recencyBonus = max(0, 1 - ($ageHours / 240));
$score = ($recentViews * 0.70) +
($velocity * 100 * 0.15) +
($recencyBonus * 50 * 0.10) +
($likeCount * 0.1 * 0.05);
$video->trending_score = round($score, 2);
$video->view_count = $recentViews;
$video->like_count = $likeCount;
return $video;
});
$trendingVideos = $videos
->filter(fn ($v) => $v->trending_score > 0)
->sortByDesc('trending_score')
->take($limit)
->values();
return view('videos.trending', [
'videos' => $trendingVideos,
'hours' => $hours,
'limit' => $limit,
]);
}
public function shorts(Request $request)
{
$videos = Video::public()
->where('is_shorts', true)
->where('status', 'ready')
->with('user')
->latest()
->get();
return view('videos.shorts', compact('videos'));
}
public function stream(Video $video)
{
// Check if user can view this video
if (! $video->canView(Auth::user())) {
abort(404, 'Video not found');
}
@@ -376,7 +433,6 @@ class VideoController extends Controller
$range = request()->header('Range');
if ($range) {
// Parse range header
preg_match('/bytes=(\d+)-(\d*)/', $range, $matches);
$start = intval($matches[1] ?? 0);
$end = $matches[2] ? intval($matches[2]) : $fileSize - 1;
@@ -404,7 +460,6 @@ class VideoController extends Controller
fclose($handle);
exit;
} else {
// No range requested, stream entire file
header('Content-Type: '.$mimeType);
header('Content-Length: '.$fileSize);
header('Accept-Ranges: bytes');
@@ -416,96 +471,54 @@ class VideoController extends Controller
}
}
public function download(Video $video)
public function hls(Video $video, $file = 'playlist.m3u8')
{
// Check if user can view this video
if (! $video->canView(Auth::user())) {
abort(404, 'Video not found');
abort(404);
}
$path = storage_path('app/public/videos/'.$video->filename);
if (! file_exists($path)) {
abort(404, 'Video file not found');
if (! $video->has_hls) {
abort(404, 'HLS unavailable');
}
$filename = $video->title.'.'.pathinfo($video->filename, PATHINFO_EXTENSION);
$hlsPath = storage_path('app/' . $video->hls_path . '/' . $file);
return response()->download($path, $filename);
if (! file_exists($hlsPath)) {
abort(404);
}
$mimeType = pathinfo($hlsPath, PATHINFO_EXTENSION) === 'm3u8'
? 'application/vnd.apple.mpegurl'
: 'video/mp2t';
header('Content-Type: '.$mimeType);
header('Accept-Ranges: bytes');
header('Cache-Control: public, max-age=3600');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Range');
if (request()->header('Range')) {
$size = filesize($hlsPath);
preg_match('/bytes=(\d+)-(\d*)/', request()->header('Range'), $matches);
$start = intval($matches[1] ?? 0);
$end = $matches[2] ? intval($matches[2]) : $size - 1;
$length = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
header('Content-Length: '.$length);
header('Content-Range: bytes '.$start.'-'.$end.'/'.$size);
$handle = fopen($hlsPath, 'rb');
fseek($handle, $start);
echo fread($handle, $length);
fclose($handle);
} else {
header('Content-Length: '.filesize($hlsPath));
readfile($hlsPath);
}
exit;
}
// Trending videos page
public function trending(Request $request)
{
$hours = $request->get('hours', 48); // Default: 48 hours
$limit = $request->get('limit', 50);
// Validate parameters
$hours = min(max($hours, 24), 168); // Between 24h and 7 days
$limit = min(max($limit, 10), 100);
// Get all public ready videos first
$videos = Video::public()
->where('status', 'ready')
->where('created_at', '>=', now()->subDays(10))
->with('user')
->get();
// Calculate trending score for each video
$videos = $videos->map(function ($video) use ($hours) {
$recentViews = \DB::table('video_views')
->where('video_id', $video->id)
->where('watched_at', '>=', now()->subHours($hours))
->count();
$likeCount = \DB::table('video_likes')
->where('video_id', $video->id)
->count();
// Calculate age in hours
$ageHours = $video->created_at->diffInHours(now());
// Calculate trending score
// 70% recent views, 15% velocity, 10% recency, 5% likes
$velocity = $recentViews / $hours;
$recencyBonus = max(0, 1 - ($ageHours / 240));
$score = ($recentViews * 0.70) +
($velocity * 100 * 0.15) +
($recencyBonus * 50 * 0.10) +
($likeCount * 0.1 * 0.05);
$video->trending_score = round($score, 2);
$video->view_count = $recentViews;
$video->like_count = $likeCount;
return $video;
});
// Filter and sort by trending score
$trendingVideos = $videos
->filter(fn ($v) => $v->trending_score > 0)
->sortByDesc('trending_score')
->take($limit)
->values();
return view('videos.trending', [
'videos' => $trendingVideos,
'hours' => $hours,
'limit' => $limit,
]);
}
// Shorts page
public function shorts(Request $request)
{
$videos = Video::public()
->where('is_shorts', true)
->where('status', 'ready')
->with('user')
->latest()
->get();
return view('videos.shorts', compact('videos'));
}
// Add download, trending, shorts from original as needed...
}
+28 -16
View File
@@ -5,6 +5,7 @@ namespace App\Jobs;
use App\Models\Video;
use FFMpeg\FFMpeg;
use FFMpeg\Format\Video\X264;
use Illuminate\Support\Facades\Config;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -27,10 +28,10 @@ class CompressVideoJob implements ShouldQueue
public function handle()
{
$video = $this->video;
// Get original file path
$originalPath = storage_path('app/' . $video->path);
if (!file_exists($originalPath)) {
Log::error('CompressVideoJob: Original file not found: ' . $originalPath);
return;
@@ -43,39 +44,47 @@ class CompressVideoJob implements ShouldQueue
try {
$ffmpeg = FFMpeg::create();
$ffmpegVideo = $ffmpeg->open($originalPath);
// Use CRF 18 for high quality (lower = better quality, 18-23 is good range)
// Use 'slow' preset for better compression efficiency
$format = new X264('aac', 'libx264');
$format->setKiloBitrate(0); // 0 = use CRF
$format->setAudioKiloBitrate(192);
// Add CRF option for high quality
// GPU NVENC encoding via config
$ffmpegConfig = Config::get('ffmpeg');
$videoPasses = $ffmpegConfig['defaults']['video'] ?? [];
$audioPasses = $ffmpegConfig['defaults']['audio'] ?? [];
$format = new X264('aac', 'h264_nvenc');
foreach ($videoPasses as $pass) {
$format->addLegacyOption($pass);
}
foreach ($audioPasses as $pass) {
$format->addLegacyOption($pass);
}
$ffmpegVideo->save($format, $compressedPath);
// Check if compressed file was created and is smaller
if (file_exists($compressedPath)) {
$originalSize = filesize($originalPath);
$compressedSize = filesize($compressedPath);
// Only use compressed file if it's smaller
if ($compressedSize < $originalSize) {
// Delete original and rename compressed
unlink($originalPath);
rename($compressedPath, $originalPath);
// Update video record
$video->update([
'size' => $compressedSize,
'filename' => $video->filename, // Keep same filename
'mime_type' => 'video/mp4',
]);
Log::info('CompressVideoJob: Video compressed successfully', [
Log::info('CompressVideoJob: Video compressed with GPU NVENC', [
'video_id' => $video->id,
'original_size' => $originalSize,
'compressed_size' => $compressedSize,
'saved' => round(($originalSize - $compressedSize) / $originalSize * 100) . '%'
'saved' => round(($originalSize - $compressedSize) / $originalSize * 100) . '%',
'encoder' => 'h264_nvenc'
]);
} else {
// Compressed file is larger, delete it
@@ -83,9 +92,12 @@ class CompressVideoJob implements ShouldQueue
Log::info('CompressVideoJob: Compression made file larger, keeping original');
}
}
$video->update(['status' => 'ready']);
// Chain to HLS generation for GPU-accelerated adaptive playback
\App\Jobs\GenerateHlsJob::dispatch($video);
} catch (\Exception $e) {
Log::error('CompressVideoJob failed: ' . $e->getMessage());
$video->update(['status' => 'ready']); // Mark as ready anyway
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Jobs;
use App\Models\Video;
use FFMpeg\FFMpeg;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class GenerateHlsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $video;
public function __construct(Video $video)
{
$this->video = $video;
$this->onQueue('video-processing');
}
public function handle()
{
$video = $this->video->fresh();
if ($video->status !== 'ready') {
Log::warning('GenerateHlsJob: Video not ready', ['id' => $video->id]);
return;
}
$sourcePath = storage_path('app/' . $video->path);
if (!file_exists($sourcePath)) {
Log::error('GenerateHlsJob: Source file missing', ['path' => $sourcePath]);
return;
}
$hlsDir = 'public/hls/' . $video->id;
$hlsPath = storage_path('app/' . $hlsDir);
// Clean existing HLS
if (is_dir($hlsPath)) {
Storage::deleteDirectory($hlsDir);
}
Storage::makeDirectory($hlsDir);
try {
$ffmpegConfig = Config::get('ffmpeg');
$ffmpeg = FFMpeg::create([
'ffmpeg.binaries' => $ffmpegConfig['ffmpeg'] ?? '/usr/bin/ffmpeg',
'ffprobe.binaries' => $ffmpegConfig['ffprobe'] ?? '/usr/bin/ffprobe',
'timeout' => $ffmpegConfig['timeout'] ?? 3600,
]);
$videoMedia = $ffmpeg->open($sourcePath);
// HLS variants: 480p, 720p, 1080p
$variants = [
[
'height' => 480,
'name' => '480p',
'bitrate' => 1000,
],
[
'height' => 720,
'name' => '720p',
'bitrate' => 2500,
],
[
'height' => 1080,
'name' => '1080p',
'bitrate' => 5000,
],
];
$hlsOptions = [
'-c:v h264_nvenc',
'-preset p4',
'-g 48', // GOP size 2s @25fps
'-sc_threshold 0',
'-c:a aac',
'-ar 48000',
'-f hls',
'-hls_time 6',
'-hls_list_size 0',
'-hls_segment_filename',
'%v/%03d.ts',
'-hls_flags',
'delete_segments+append_list',
'-master_pl_name',
'playlist.m3u8',
];
$videoMedia->save(new \FFMpeg\Format\Video\X264(), $hlsPath, function ($filters) use ($variants) {
foreach ($variants as $variant) {
$filters->custom('-map 0:v:0 -map 0:a:0?')
->size("trunc(oh*a/oh/{$variant['height']})*{$variant['height']}") // Scale
->resize(new \FFMpeg\Coordinate\Dimension($variant['height'] * 16 / 9, $variant['height']))
->videoCodec($variant['bitrate'] . 'k')
->addLegacyOption('-var_stream_map v:0,name:' . $variant['name'] . ' v:1,name:720p v:2,name:1080p');
}
});
// Mark HLS ready
$video->update([
'has_hls' => true,
'hls_path' => $hlsDir,
]);
Log::info('GenerateHlsJob: HLS generated successfully', [
'video_id' => $video->id,
'variants' => array_column($variants, 'name'),
'hls_url' => asset('storage/' . $hlsDir . '/playlist.m3u8'),
]);
} catch (\Exception $e) {
Log::error('GenerateHlsJob failed: ' . $e->getMessage(), ['video_id' => $video->id]);
Storage::deleteDirectory($hlsDir);
}
}
}
+3
View File
@@ -23,6 +23,8 @@ class Video extends Model
'visibility',
'type',
'is_shorts',
'has_hls',
'hls_path',
];
protected $casts = [
@@ -31,6 +33,7 @@ class Video extends Model
'width' => 'integer',
'height' => 'integer',
'is_shorts' => 'boolean',
'has_hls' => 'boolean',
];
// Relationships