Introduce per-video language support and multiple audio tracks (VideoAudioTrack model + migrations for language, description, title), a reusable language-select component, and a track-editor form. Bundle the self-hosted flag-icons v7.2.3 library and a NAS auto-sync command. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
20 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
TAKEONE (Play) is a Laravel 10 video-sharing platform with sports match annotation, HLS adaptive streaming, GPU-accelerated video processing, playlists, threaded comments, and a super-admin panel. Live at https://video.takeone.bh.
Tech stack: PHP 8.1+, Laravel 10, Blade templating, Vite 5, Axios, FFmpeg/FFProbe with NVIDIA NVENC, SQLite (dev) / MySQL (prod), Laravel Sanctum.
Essential Commands
Local Development
php artisan serve # Backend on http://localhost:8000
npm run dev # Vite dev server with HMR
npm run build # Production frontend build → public/build/
Database
php artisan migrate
php artisan db:seed
php artisan tinker
Background Workers
# Video processing (CompressVideoJob, GenerateHlsJob)
php artisan queue:work --queue=video-processing
# Orphaned file cleanup scheduler (every CLEANUP_INTERVAL_MINUTES, default 30)
php artisan schedule:run # run this every minute via cron
php artisan cleanup:orphaned-videos --dry-run # preview only
php artisan cleanup:orphaned-videos --force # delete orphans
Testing
./vendor/bin/phpunit
./vendor/bin/phpunit --filter "TestName"
./vendor/bin/phpunit tests/Feature/ExampleTest.php
Tests use in-memory SQLite, array mail/cache/session drivers, sync queue, and BCRYPT_ROUNDS=4. Set APP_ENV=testing.
Architecture
Role System
Three roles stored on users.role: super_admin, admin, user (null = user). The IsSuperAdmin middleware guards all /admin/* routes. Helper methods on the User model: isSuperAdmin(), isAdmin(), isUser().
Video Lifecycle
VideoController@storevalidates upload, stores file, extracts metadata via FFProbe (duration, dimensions, orientation).- Status column transitions:
pending → processing → ready(orfailed). CompressVideoJobre-encodes with NVIDIA NVENC (h264_nvenc, CRF 23), replaces original if smaller.GenerateHlsJobproduces 480p / 720p / 1080p HLS variants (h264_nvenc, preset p4) as.m3u8+.tsfiles.- Streaming served at
GET /videos/{video}/hls/{file?}(master playlist → segments).
Queue connection is sync by default (runs inline); switch QUEUE_CONNECTION=database or redis for true async.
Shorts Auto-Detection
A video is a Short when duration ≤ 60 s and portrait orientation. The is_shorts DB column allows manual override. Use model scopes Video::shorts() / Video::notShorts().
Trending Algorithm
Video::scopeTrending($hours=48, $limit=50) — weighted score: 70% recent views, 15% view velocity, 10% recency bonus, 5% likes. Only applies to videos < 10 days old with ≥ 5 recent views.
Playlist System
playlist_videospivot carriesposition,watched_seconds,watched,added_at,last_watched_at.- Each user has one
is_default = trueplaylist ("Watch Later"). Playlistmodel methods:addVideo(),removeVideo(),reorder(),getNextVideo(),getPreviousVideo(),updateWatchProgress(),canView(),canEdit().
Comment Threading & Mentions
Comments have a parent_id for one-level threading (replies). The parsed_body accessor converts @username syntax into clickable profile links.
Comment Timestamp Badges
The enhanceBody() function in components/video-comments.blade.php converts timestamp syntax written in comments into clickable ._comment-time-badge spans at render time (client-side). Supported formats:
@mm:ss— single timestamp, jumps to that point (colon separator)@mm.ss— same, dot separator (legacy, still supported)@mm:ss-mm:ssor@mm.ss-mm.ss— time range; plays from start to end then pauses
Clicking a badge: scrolls to #ytpWrap (smooth), waits 500 ms, seeks #videoPlayer to start, calls .play(), and if a range is specified stops at end via a timeupdate listener. @username mention detection requires the first char to be a letter so it never collides with numeric timestamps.
Sports Match Annotation
Videos of type match support three related models:
MatchRound— round number, name,start_time_secondsMatchPoint—timestamp_seconds, action, competitor (blue/red), running scoreCoachReview— time-range segment with coach note and emoji
All managed via MatchEventController under authenticated routes.
Key Model Scopes & Accessors
Video scopes: public(), visibleTo($user), shorts(), notShorts(), trending().
Video accessors: url, thumbnail_url, like_count, view_count, formatted_duration, iso_duration, open_graph_image.
Playlist accessors: thumbnail_url, video_count, total_duration, formatted_duration.
Rules
Never navigate between videos with a page refresh — all video-to-video transitions (Up Next recommendations, playlist tracks, prev/next) must use JavaScript SPA transitions. Never use window.location.href or <a> tags with hard navigation for video card clicks. The established pattern is:
- Video player (generic, match types):
recTransitionTo(url)/plTransitionTo(url)— fetch/videos/{key}/player-dataJSON, callwindow._ytpLoadSource(hlsUrl, mp4Url), thenrecSwapContent(url)/plSwapContent(url)in the background to update description, comments, and sidebar. - Audio player (music type): same pattern but swap
audio.srcandaudio.play()instead of_ytpLoadSource. - Sidebar cards must have
data-rec-url(Up Next) ordata-pl-id(playlist) attributes and callrecGoTo(url)/plGoTo(url)onclick — neverwindow.location.href. - Autoplay on track end is wired via
window._plOnVideoEnd(video) orwindow._plOnTrackEnd(audio) hooks — the player calls these hooks onended; the SPA script sets them. - The only fallback to
window.location.hrefis insidecatchblocks when the fetch itself fails.
Database changes require confirmation — if any task requires a migration, schema change, or new column, always ask before proceeding.
Never use alert(), confirm(), or prompt() — use toast notifications or inline UI feedback instead.
All buttons must use the global .action-btn system — never add custom button CSS. Use these classes:
.action-btn— default (bordered, bg-secondary).action-btn.action-btn-primaryor.action-btn.primary— brand red, for primary/submit actions.action-btn.action-btn-dangeror.action-btn.danger— red border/text, for destructive actions.action-btn.icon-only— square padding, for icon-only buttons
Structure: <button class="action-btn"><i class="bi bi-..."></i> <span>Label</span></button>. The global CSS lives in layouts/app.blade.php.
Mobile layout uses a native-app scroll model — on max-width: 768px, html and body are locked (overflow: hidden; position: fixed) so the window never scrolls. .yt-main is position: fixed spanning top: 56px to bottom: calc(56px + env(safe-area-inset-bottom)) with overflow-y: auto; -webkit-overflow-scrolling: touch. This keeps the header and bottom nav truly fixed without any JavaScript. Consequences to remember:
- Never use
position: stickyinside.yt-mainon mobile — sticky elements float over content because the scroll container changed. Override withposition: relative !importantin the mobile media query. - Never rely on
window.scrollYorwindow.scrollevents on mobile — the window doesn't scroll; listen ondocument.getElementById('main')instead. - Bottom nav needs no JS transform — since the window is locked, browser chrome animation never shifts fixed elements.
Upload modal and upload page must always stay in sync — the desktop upload UI lives in resources/views/layouts/partials/upload-modal.blade.php and the mobile upload UI lives in resources/views/videos/create.blade.php. On mobile, openUploadModal() redirects to the create page instead of showing the modal. Any change made to one must be applied to the other immediately in the same task.
Edit modal and edit page must always stay in sync — the desktop edit UI lives in resources/views/layouts/partials/edit-video-modal.blade.php and the mobile edit UI lives in resources/views/videos/edit.blade.php. On mobile (< 992px), openEditVideoModal(videoId) redirects to /videos/{id}/edit instead of opening the modal. Any change made to one must be applied to the other immediately in the same task. — the desktop upload UI lives in resources/views/layouts/partials/upload-modal.blade.php and the mobile upload UI lives in resources/views/videos/create.blade.php. On mobile, openUploadModal() redirects to the create page instead of showing the modal. Any change made to one must be applied to the other immediately in the same task — this includes new fields, validation logic, file-type support, JS behaviour, labels, and error handling. Never update only one side.
Never build custom dropdowns for country, nationality, phone code, timezone, currency, or language — reusable Blade components already exist for these. Always use them; never roll a new <select>, inline list, or custom picker:
| Need | Component | Stored value |
|---|---|---|
| Country / nationality picker | <x-country-select name="…" /> |
ISO2 code e.g. "BH" |
| Phone / dial-code picker | <x-phone-code-select name="…" /> |
`"+973 |
| Timezone picker | <x-timezone-select name="…" /> |
IANA string e.g. "Asia/Bahrain" |
| Currency | read from App\Data\Countries::all()[$iso2]['currency'] |
ISO 4217 code e.g. "BHD" |
| Language picker | <x-language-select name="…" /> |
ISO 639-1 code e.g. "ar", "en" |
All four select components accept name, id, value, label, placeholder, required, class, and style props. Country/phone/timezone data lives in app/Data/Countries.php; language data lives in app/Data/Languages.php. Usage is tracked in .claude/component-usage.md — add a row to the relevant table whenever you place one of these components in a view.
Component usage tracker is mandatory and must always be kept current — the tracker lives at .claude/component-usage.md. These rules apply without exception:
- Creating a new reusable component → add a new section to the tracker listing the component file path, its props, and an empty usage table.
- Placing a component in any view → immediately add a row to the relevant tracker table (view file path, field/slot name, any relevant notes). Do this in the same task, not later.
- Modifying a component (props, markup, CSS, JS, behaviour) → open the tracker first, read every row in that component's usage table, then apply the necessary follow-up changes to every listed view before marking the task done. Never modify a component without checking its tracker entries.
- Removing a component from a view → delete its row from the tracker table in the same task.
- Deleting a component entirely → remove its full section from the tracker and clean up every view that was still referencing it.
The tracker is the source of truth for blast radius. If the tracker is out of date and a change breaks an unlisted page, that is a process failure — always keep it accurate.
Always use the self-hosted flag-icons library for every flag in the project — never use emoji flags or external CDN flag sources.
The flag-icons v7.2.3 library is self-hosted at public/vendor/flag-icons/ (CSS + 270 SVG files). It is loaded synchronously in both layouts:
- Front-end:
resources/views/layouts/app.blade.phpviaasset('vendor/flag-icons/css/flag-icons.min.css') - Admin:
resources/views/admin/layout.blade.phpvia the same asset path
Rules that must never be violated:
-
Never use emoji flags (
🇧🇭,🇺🇸, etc.) anywhere — they are invisible on Windows Chrome/Firefox. Always use<span class="fi fi-{iso2}"></span>where{iso2}is a lowercase two-letter country code (e.g.bh,us,gb). -
Never load flag-icons from a CDN (
jsdelivr,unpkg,flagcdn.com, etc.). The library is already self-hosted; adding a CDN link creates a duplicate load and a network dependency. -
Countries::all()flagfield is a lowercase ISO2 code —app/Data/Countries.phpgenerates this via$f = fn(string $c) => strtolower($c). Do not change it back to emoji. Every component that renders$opt['flag']already wraps it in<span class="fi fi-{{ $opt['flag'] }}"></span>. -
Languages::all()flagfield is also a lowercase ISO2 code — e.g. Arabic →'sa', English →'gb'. Render it the same way. -
When updating JS that copies a selected flag into a button icon, always use
innerHTML, nottextContent— the flag is now an HTML<span>, not a text character. The_pick()method in the custom-select components already does this. -
For the admin chart flag overlays (
admin/dashboard.blade.php), use<span class="fi fi-{code}">elements positioned absolutely — not<img>tags fromflagcdn.com. -
Unknown/missing country fallback: always use
<span class="fi fi-xx"></span>— the library's own built-in placeholder (the SVG exists atpublic/vendor/flag-icons/flags/4x3/xx.svg). Never use any external icon, emoji, or Bootstrap Icons globe as a fallback. In Blade:<span class="fi fi-{{ $flag ?: 'xx' }}"></span>. In JS:`<span class="fi fi-${flag || 'xx'}"></span>`.
Match highlights sidebar must always match the video player height — use a ResizeObserver on #ytpWrap to write --sidebar-height to document.documentElement and bind .events-sidebar { height: var(--sidebar-height) }. Never hardcode a pixel or viewport height for the sidebar. The pattern lives in videos/types/match.blade.php (initSidebarHeightSync).
NAS with automatic local fallback
NAS is the primary storage backend. When NAS is reachable, every user file must end up on the NAS and be served from the NAS. When NAS is unreachable, files are stored locally and automatically migrated to NAS when it comes back online.
File types and their NAS locations:
| File type | NAS path | Served via |
|---|---|---|
| Video / audio | users/{slug}/videos/{title-slug}/{title-slug}.{ext} |
NasSyncService::ensureLocalCopy() |
| Video thumbnail | users/{slug}/videos/{title-slug}/thumb.{ext} |
MediaController::thumbnail + ensureLocalAsset() |
| Audio slides | users/{slug}/videos/{title-slug}/slides/{n}.{ext} |
MediaController::thumbnail + ensureLocalAsset() |
| Playlist thumbnail | users/{slug}/playlists/{playlist-id}/thumb.{ext} |
MediaController::thumbnail + ensureLocalAsset() |
| Avatar | users/{slug}/profile/avatar.{ext} |
MediaController::avatar + ensureLocalAsset() |
| Banner | users/{slug}/profile/banner.{ext} |
MediaController::banner + ensureLocalAsset() |
| Post images | users/{slug}/posts/{post-id}/{filename} |
MediaController::postImage + ensureLocalAsset() |
The only files that live permanently on local disk are HLS segments (storage/app/public/hls/{video_id}/) because they are generated locally and served directly. Everything else is NAS.
The following local directories must never exist as permanent storage. They were deleted after migration and must not be recreated as destinations:
storage/app/public/thumbnails/— formerly held video/slide/playlist thumbnails; now NAS onlystorage/app/public/avatars/— formerly held user avatars; now NAS onlystorage/app/public/videos/— formerly held uploaded video files; now NAS only
These directories may appear temporarily during an upload (as a write buffer before NAS push) and are cleaned up immediately. If you ever find files lingering there after an upload completes, it means the NAS push failed — investigate the NAS connection, do not leave files there.
Absolute rules — these must never be violated:
-
Never use
asset('storage/...')for any user file URL. Always use the named media routes:route('media.thumbnail', $path),route('media.avatar', $path),route('media.banner', $path),route('media.post-image', $path). These routes go throughMediaControllerwhich callsensureLocalAsset()and pulls from NAS automatically. -
After writing any file to local disk, immediately push it to NAS and delete the local copy. The upload flow is always: write to temp → push to NAS → delete local. Use the correct service method for each type:
- Videos/audio →
NasSyncService::uploadDirectToNas()thendeleteLocalVideo() - Thumbnails (video/slide) →
NasSyncService::putFile($tempAbs, "{$nasDir}/thumb.{$ext}")then@unlink($tempAbs), store full NAS path in DB - Playlist thumbnails →
PlaylistController::pushPlaylistThumbnailToNas()(handles mkdirp, putFile, unlink internally) - Avatars →
NasSyncService::syncAvatar()thendeleteLocalAvatar() - Banners →
NasSyncService::syncBanner()thendeleteLocalBanner() - Post images →
NasSyncService::syncPostImages()thendeleteLocalPostImages()
- Videos/audio →
-
Always store the full NAS relative path in the DB, never just the filename. The DB column must contain the full
users/...path (e.g.users/hanzo-hattori-bfnmwq/videos/my-title/thumb.png). Storing only the basename (e.g.thumb.pngor a UUID filename) is the legacy format that breaks NAS serving and the MediaController fallback logic. -
Never call
putFile()directly for video/audio uploads. Always useuploadDirectToNas()— it resolves the correctusers/...directory, writesmeta.json, and updates the DBpathandfilenamecolumns. CallingputFile()with a manually constructed path will create files in the wrong location that the streaming layer cannot find. -
Set
video->status = 'ready'before dispatchingGenerateHlsJobfor NAS uploads. The job checksif ($video->status !== 'ready') returnand silently does nothing otherwise. For NAS, the upload is the compression step — the video is ready as soon asuploadDirectToNas()completes. For local storage,CompressVideoJobhandles the status transition automatically. -
Always check
NasSyncService::isEnabled()before doing a NAS operation. It returnsfalsewhen NAS is unreachable (TCP port-445 check, cached 2 minutes) or when the setting is disabled. Code withif ($nas->isEnabled())branches that fall back to local storage is correct — thenas:auto-syncscheduler will migrate local files to NAS when it comes back online.
If you find legacy local files that should be on NAS, follow this migration procedure (same pattern used to clean up thumbnails and avatars):
- Identify which DB record owns each local file (
Video::where('thumbnail', $filename),User::where('avatar', $filename), etc.) - For each owned file: call
NasSyncService::mkdirp($nasDir)thenputFile($localAbs, $nasPath)then@unlink($localAbs), then update the DB record to the full NAS path - Delete files with no DB match (orphans) directly with
@unlink() - Once a directory is empty,
rmdir()it — do not leave empty legacy directories - For playlists: use
PlaylistController::pushPlaylistThumbnailToNas()or replicate its pattern (mkdirp+putFile+unlink)
Infrastructure Notes
- Cloudflare proxy:
AppServiceProviderforces HTTPS and trusts Cloudflare headers viaTrustProxies. - FFmpeg config:
/config/ffmpeg.php— binaries at/usr/bin/ffmpegand/usr/bin/ffprobe, GPU device 0, 3600 s timeout. - Broadcasting: Pusher is configured but
BroadcastServiceProvideris commented out — not active. - Timezone:
Asia/Bahrain(set inconfig/app.php). - App name constant:
config('app.name')returnsTAKEONE.
Route Structure Summary
- Public:
/,/videos,/trending,/shorts,/videos/search,/videos/{video}, stream/hls/download - Auth-required: video CRUD, likes, comments, profile, settings, history, playlists, match events
- Admin (
/admin/*,super_adminmiddleware): dashboard, user CRUD, video CRUD, orphan cleanup - API:
GET /api/user(Sanctum token auth)