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

+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...
}