latest update

This commit is contained in:
ghassan committed 2026-03-11 11:21:33 +03:00
1 parent 9ad842dcd5
commit 062c0e896f
42 files changed
+7052 -2921

No files matched your search

+321
View File
@@ -0,0 +1,321 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Playlist extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'description',
'thumbnail',
'visibility',
'is_default',
];
protected $casts = [
'is_default' => 'boolean',
];
// Relationships
public function user()
{
return $this->belongsTo(User::class);
}
public function videos()
{
return $this->belongsToMany(Video::class, 'playlist_videos')
->withPivot('position', 'watched_seconds', 'watched', 'added_at', 'last_watched_at')
->orderBy('position');
}
// Get videos with their pivot data
public function getVideosWithPivot()
{
return $this->videos()->orderBy('position')->get();
}
// Accessors
public function getThumbnailUrlAttribute()
{
if ($this->thumbnail) {
return asset('storage/thumbnails/'.$this->thumbnail);
}
// Generate a placeholder based on playlist name
return 'https://ui-avatars.com/api/?name='.urlencode($this->name).'&background=random&size=200';
}
// Get total video count
public function getVideoCountAttribute()
{
return $this->videos()->count();
}
// Get total duration of all videos in playlist
public function getTotalDurationAttribute()
{
return $this->videos()->sum('duration');
}
// Get formatted total duration (e.g., "2h 30m")
public function getFormattedDurationAttribute()
{
$totalSeconds = $this->total_duration;
if (! $totalSeconds) {
return '0m';
}
$hours = floor($totalSeconds / 3600);
$minutes = floor(($totalSeconds % 3600) / 60);
if ($hours > 0) {
return "{$hours}h {$minutes}m";
}
return "{$minutes}m";
}
// Get total views of all videos in playlist
public function getTotalViewsAttribute()
{
return $this->videos()->get()->sum('view_count');
}
// Check if user owns this playlist
public function isOwnedBy($user)
{
if (! $user) {
return false;
}
return $this->user_id === $user->id;
}
// Check if video is in this playlist
public function hasVideo(Video $video)
{
return $this->videos()->where('video_id', $video->id)->exists();
}
// Get video position in playlist
public function getVideoPosition(Video $video)
{
$pivot = $this->videos()->where('video_id', $video->id)->first();
return $pivot ? $pivot->pivot->position : null;
}
// Get next video in playlist
public function getNextVideo(Video $currentVideo)
{
$currentPosition = $this->getVideoPosition($currentVideo);
if ($currentPosition === null) {
return $this->videos()->first();
}
return $this->videos()
->wherePivot('position', '>', $currentPosition)
->orderBy('position')
->first();
}
// Get previous video in playlist
public function getPreviousVideo(Video $currentVideo)
{
$currentPosition = $this->getVideoPosition($currentVideo);
if ($currentPosition === null) {
return $this->videos()->last();
}
return $this->videos()
->wherePivot('position', '<', $currentPosition)
->orderByDesc('position')
->first();
}
// Get shareable URL
public function getShareUrlAttribute()
{
return route('playlists.show', $this->id);
}
// Scope for public playlists
public function scopePublic($query)
{
return $query->where('visibility', 'public');
}
// Scope for user's playlists
public function scopeForUser($query, $userId)
{
return $query->where('user_id', $userId);
}
// Scope for default playlists (Watch Later)
public function scopeDefault($query)
{
return $query->where('is_default', true);
}
// Visibility helpers
public function isPublic()
{
return $this->visibility === 'public';
}
public function isPrivate()
{
return $this->visibility === 'private';
}
// Check if user can view this playlist
public function canView($user = null)
{
// Owner can always view
if ($user && $this->user_id === $user->id) {
return true;
}
// Public playlists can be viewed by anyone
return $this->visibility === 'public';
}
// Check if user can edit this playlist
public function canEdit($user = null)
{
return $user && $this->user_id === $user->id;
}
// Update video positions after reordering
public function reorderVideos($videoIds)
{
foreach ($videoIds as $index => $videoId) {
$this->videos()->updateExistingPivot($videoId, ['position' => $index]);
}
}
// Add video to playlist
public function addVideo(Video $video)
{
if ($this->hasVideo($video)) {
return false;
}
$maxPosition = $this->videos()->max('position') ?? -1;
$this->videos()->attach($video->id, [
'position' => $maxPosition + 1,
'added_at' => now(),
]);
return true;
}
// Remove video from playlist
public function removeVideo(Video $video)
{
if (! $this->hasVideo($video)) {
return false;
}
$this->videos()->detach($video->id);
// Reorder remaining videos
$this->reorderPositions();
return true;
}
// Reorder positions after removal
protected function reorderPositions()
{
$videos = $this->videos()->orderBy('position')->get();
$position = 0;
foreach ($videos as $video) {
$this->videos()->updateExistingPivot($video->id, ['position' => $position]);
$position++;
}
}
// Update watch progress for a video in playlist
public function updateWatchProgress(Video $video, $seconds)
{
$pivot = $this->videos()->where('video_id', $video->id)->first()?->pivot;
if ($pivot) {
$pivot->watched_seconds = $seconds;
$pivot->last_watched_at = now();
// Mark as watched if 90% complete
if ($video->duration && $seconds >= ($video->duration * 0.9)) {
$pivot->watched = true;
}
$pivot->save();
}
}
// Get watch progress for a video in playlist
public function getWatchProgress(Video $video)
{
$pivot = $this->videos()->where('video_id', $video->id)->first()?->pivot;
return $pivot ? [
'watched_seconds' => $pivot->watched_seconds,
'watched' => $pivot->watched,
'last_watched_at' => $pivot->last_watched_at,
] : null;
}
// Get first unwatched video
public function getFirstUnwatchedVideo()
{
return $this->videos()
->wherePivot('watched', false)
->orderBy('position')
->first();
}
// Get random video (for shuffle)
public function getRandomVideo()
{
return $this->videos()->inRandomOrder()->first();
}
// Static method to create default "Watch Later" playlist
public static function createWatchLater($userId)
{
return self::create([
'user_id' => $userId,
'name' => 'Watch Later',
'description' => 'Save videos to watch later',
'visibility' => 'private',
'is_default' => true,
]);
}
// Get or create watch later playlist for user
public static function getWatchLater($userId)
{
$playlist = self::where('user_id', $userId)
->where('is_default', true)
->first();
if (! $playlist) {
$playlist = self::createWatchLater($userId);
}
return $playlist;
}
}
+53 -3
View File
@@ -19,6 +19,16 @@ class User extends Authenticatable
'password',
'avatar',
'role',
'bio',
'website',
'twitter',
'instagram',
'facebook',
'youtube',
'linkedin',
'tiktok',
'birthday',
'location',
];
protected $hidden = [
@@ -52,12 +62,18 @@ class User extends Authenticatable
return $this->hasMany(Comment::class);
}
public function playlists()
{
return $this->hasMany(Playlist::class);
}
public function getAvatarUrlAttribute()
{
if ($this->avatar) {
return asset('storage/avatars/' . $this->avatar);
return asset('storage/avatars/'.$this->avatar);
}
return 'https://i.pravatar.cc/150?u=' . $this->id;
return 'https://i.pravatar.cc/150?u='.$this->id;
}
// Role helper methods
@@ -82,5 +98,39 @@ class User extends Authenticatable
// For now, return a placeholder - in production this would come from a subscriptions table
return rand(100, 10000);
}
}
// Get social links as an array
public function getSocialLinksAttribute()
{
return [
'twitter' => $this->twitter,
'instagram' => $this->instagram,
'facebook' => $this->facebook,
'youtube' => $this->youtube,
'linkedin' => $this->linkedin,
'tiktok' => $this->tiktok,
];
}
// Check if user has any social links
public function hasSocialLinks()
{
return $this->twitter || $this->instagram || $this->facebook ||
$this->youtube || $this->linkedin || $this->tiktok;
}
// Get formatted website URL
public function getWebsiteUrlAttribute()
{
if (! $this->website) {
return null;
}
// Add https:// if no protocol is specified
if (! preg_match('/^https?:\/\//', $this->website)) {
return 'https://'.$this->website;
}
return $this->website;
}
}
+172 -38
View File
@@ -22,6 +22,7 @@ class Video extends Model
'status',
'visibility',
'type',
'is_shorts',
];
protected $casts = [
@@ -29,6 +30,7 @@ class Video extends Model
'size' => 'integer',
'width' => 'integer',
'height' => 'integer',
'is_shorts' => 'boolean',
];
// Relationships
@@ -52,21 +54,26 @@ class Video extends Model
// Accessors
public function getUrlAttribute()
{
return asset('storage/videos/' . $this->filename);
return asset('storage/videos/'.$this->filename);
}
public function getThumbnailUrlAttribute()
{
if ($this->thumbnail) {
return asset('storage/thumbnails/' . $this->thumbnail);
return asset('storage/thumbnails/'.$this->thumbnail);
}
return asset('images/video-placeholder.jpg');
// Return null when no thumbnail - social platforms will use their own preview
return null;
}
// Check if video is liked by user
public function isLikedBy($user)
{
if (!$user) return false;
if (! $user) {
return false;
}
return $this->likes()->where('user_id', $user->id)->exists();
}
@@ -88,6 +95,33 @@ class Video extends Model
return route('videos.show', $this->id);
}
// Get formatted duration (e.g., "1:30" or "0:45" for shorts)
public function getFormattedDurationAttribute()
{
if (! $this->duration) {
return null;
}
$minutes = floor($this->duration / 60);
$seconds = $this->duration % 60;
return sprintf('%d:%02d', $minutes, $seconds);
}
// Get Shorts badge
public function getShortsBadgeAttribute()
{
if ($this->isShorts()) {
return [
'icon' => 'bi-collection-play-fill',
'label' => 'SHORTS',
'color' => '#ff0000',
];
}
return null;
}
// Visibility helpers
public function isPublic()
{
@@ -135,16 +169,17 @@ class Video extends Model
if ($user) {
return $query->where(function ($q) use ($user) {
$q->where('visibility', '!=', 'private')
->orWhere('user_id', $user->id);
->orWhere('user_id', $user->id);
});
}
return $query->where('visibility', '!=', 'private');
}
// Video type helpers
public function getTypeIconAttribute()
{
return match($this->type) {
return match ($this->type) {
'music' => 'bi-music-note',
'match' => 'bi-trophy',
default => 'bi-film',
@@ -153,7 +188,7 @@ class Video extends Model
public function getTypeSymbolAttribute()
{
return match($this->type) {
return match ($this->type) {
'music' => '🎵',
'match' => '🏆',
default => '🎬',
@@ -175,6 +210,31 @@ class Video extends Model
return $this->type === 'match';
}
// Shorts helpers
public function isShorts()
{
return $this->is_shorts === true || $this->is_shorts === 1 || $this->is_shorts === '1';
}
// Scope for shorts videos
public function scopeShorts($query)
{
return $query->where('is_shorts', true);
}
// Scope for non-shorts videos
public function scopeNotShorts($query)
{
return $query->where('is_shorts', false);
}
// Check if video qualifies as shorts (auto-detection)
public function qualifiesAsShorts()
{
// Shorts: duration <= 60 seconds AND portrait orientation
return $this->duration <= 60 && $this->orientation === 'portrait';
}
// Comments relationship
public function comments()
{
@@ -185,69 +245,143 @@ class Video extends Model
{
return $this->comments()->count();
}
}
// Get recent views count (within hours)
public function getRecentViews( = 48)
public function getRecentViews($hours = 48)
{
return \DB::table('video_views')
->where('video_id', ->id)
->where('watched_at', '>=', now()->subHours())
->where('video_id', $this->id)
->where('watched_at', '>=', now()->subHours($hours))
->count();
}
// Get views in last 24 hours (for velocity calculation)
public function getViewsLast24Hours()
{
return ->getRecentViews(24);
return $this->getRecentViews(24);
}
// Calculate trending score (YouTube-style algorithm)
public function getTrendingScore( = 48)
public function getTrendingScore($hours = 48)
{
= ->getRecentViews();
$recentViews = $this->getRecentViews($hours);
// Don't include videos older than 10 days
if (->created_at->diffInDays(now()) > 10) {
if ($this->created_at->diffInDays(now()) > 10) {
return 0;
}
// Don't include videos with no recent views
if ( < 5) {
if ($recentViews < 5) {
return 0;
}
// Calculate view velocity (views per hour in last 48 hours)
= / ;
$velocity = $recentViews / $hours;
// Recency bonus: newer videos get a boost
= ->created_at->diffInHours(now());
= max(0, 1 - ( / 240)); // Decreases over 10 days
$ageHours = $this->created_at->diffInHours(now());
$recencyBonus = max(0, 1 - ($ageHours / 240)); // Decreases over 10 days
// Like count bonus
= ->like_count * 0.1;
$likeBonus = $this->like_count * 0.1;
// Calculate final score
// Weight: 70% recent views, 15% velocity, 10% recency, 5% likes
= ( * 0.70) +
( * 100 * 0.15) +
( * 50 * 0.10) +
( * 0.05);
return round(, 2);
$score = ($recentViews * 0.70) +
($velocity * 100 * 0.15) +
($recencyBonus * 50 * 0.10) +
($likeBonus * 0.05);
return round($score, 2);
}
// Get thumbnail dimensions for Open Graph
public function getThumbnailWidthAttribute()
{
// Default OG recommended size is 1200x630
return $this->width ?? 1280;
}
public function getThumbnailHeightAttribute()
{
// Default OG recommended size is 1200x630
return $this->height ?? 720;
}
// Get video stream URL for Open Graph
public function getStreamUrlAttribute()
{
return route('videos.stream', $this->id);
}
// Get secure share URL
public function getSecureShareUrlAttribute()
{
return secure_url(route('videos.show', $this->id));
}
// Get secure thumbnail URL
public function getSecureThumbnailUrlAttribute()
{
if ($this->thumbnail) {
return secure_asset('storage/thumbnails/'.$this->thumbnail);
}
return null;
}
// Get full thumbnail URL with dimensions for Open Graph
public function getOpenGraphImageAttribute()
{
$thumbnail = $this->thumbnail_url;
// Add cache busting for dynamic thumbnails
if ($this->thumbnail) {
$thumbnail .= '?v='.$this->updated_at->timestamp;
}
return $thumbnail;
}
// Get author/uploader name
public function getAuthorNameAttribute()
{
return $this->user ? $this->user->name : config('app.name');
}
// Get video duration in ISO 8601 format for Open Graph
public function getIsoDurationAttribute()
{
if (! $this->duration) {
return null;
}
$hours = floor($this->duration / 3600);
$minutes = floor(($this->duration % 3600) / 60);
$seconds = $this->duration % 60;
if ($hours > 0) {
return sprintf('PT%dH%dM%dS', $hours, $minutes, $seconds);
} elseif ($minutes > 0) {
return sprintf('PT%dM%dS', $minutes, $seconds);
}
return sprintf('PT%dS', $seconds);
}
// Scope for trending videos
public function scopeTrending(, = 48, = 50)
public function scopeTrending($query, $hours = 48, $limit = 50)
{
return ->public()
return $query->public()
->where('status', 'ready')
->where('created_at', '>=', now()->subDays(10))
->orderByDesc(\DB::raw('(
(SELECT COUNT(*) FROM video_views vv WHERE vv.video_id = videos.id AND vv.watched_at >= DATE_SUB(NOW(), INTERVAL ' . . ' HOUR)) * 0.70 +
(SELECT COUNT(*) FROM video_views vv WHERE vv.video_id = videos.id AND vv.watched_at >= DATE_SUB(NOW(), INTERVAL ' . . ' HOUR)) / ' . . ' * 100 * 0.15 +
GREATEST(0, 1 - TIMESTAMPDIFF(HOUR, videos.created_at, NOW()) / 240) * 50 * 0.10 +
(SELECT COUNT(*) FROM video_views vv WHERE vv.video_id = videos.id AND vv.watched_at >= DATE_SUB(NOW(), INTERVAL '.$hours.' HOUR)) * 0.70 +
(SELECT COUNT(*) FROM video_views vv WHERE vv.video_id = videos.id AND vv.watched_at >= DATE_SUB(NOW(), INTERVAL '.$hours.' HOUR)) / '.$hours.' * 100 * 0.15 +
GREATEST(0, TIMESTAMPDIFF(HOUR, videos.created_at, NOW()) / 240) * 50 * 0.10 +
(SELECT COUNT(*) FROM video_likes vl WHERE vl.video_id = videos.id) * 0.1 * 0.05
)'))
->limit();
->limit($limit);
}
}