mirror of
https://github.com/KuekHaoYang/KVideo.git
synced 2026-08-15 00:33:44 +08:00
Refactor README and remove old documentation files
- Updated README.md to provide a comprehensive overview of the KVideo project, including features, installation instructions, and architecture. - Removed outdated README_NEW.md, SETUP.md, SUMMARY.md, and TODO.md files to streamline project documentation. - Enhanced project structure and core components descriptions in the README for better clarity and usability.
This commit is contained in:
@@ -1,106 +0,0 @@
|
||||
# Icon System Update - Liquid Glass Design
|
||||
|
||||
## Summary
|
||||
Replaced all emoji icons throughout the KVideo application with proper SVG icons following the Liquid Glass design system principles. All icons now use consistent stroke-width, sizing, and styling.
|
||||
|
||||
## Changes Made
|
||||
|
||||
### 1. Created New Icon Component System
|
||||
**File:** `components/ui/Icon.tsx`
|
||||
- Created comprehensive icon library with reusable SVG components
|
||||
- All icons follow Liquid Glass aesthetic:
|
||||
- Consistent 2px stroke width
|
||||
- Round line caps and joins
|
||||
- Scalable size prop
|
||||
- Proper className support for styling
|
||||
- Icons included:
|
||||
- Film (replaces 🎬)
|
||||
- TV (replaces 📺)
|
||||
- Search (replaces 🔍)
|
||||
- List (replaces 📑)
|
||||
- Calendar (replaces 📅)
|
||||
- Globe (replaces 🌍)
|
||||
- Zap (replaces ⚡)
|
||||
- Target (replaces 🎯)
|
||||
- Sparkles (replaces ✨)
|
||||
- Inbox (replaces 📭)
|
||||
- Play (replaces ▶️)
|
||||
- ChevronLeft (replaces ←)
|
||||
|
||||
### 2. Updated Main Page (`app/page.tsx`)
|
||||
- **Logo**: Replaced 🎬 emoji with favicon.ico image
|
||||
- **Search Button**: Replaced 🔍 with `Icons.Search`
|
||||
- **Empty Video Poster**: Replaced 🎬 with `Icons.Film`
|
||||
- **Calendar Badge**: Replaced 📅 with `Icons.Calendar` + text
|
||||
- **Empty State Hero**: Replaced 🎬 with `Icons.Film`
|
||||
- **Feature Cards**:
|
||||
- ⚡ → `Icons.Zap`
|
||||
- 🎯 → `Icons.Target`
|
||||
- ✨ → `Icons.Sparkles`
|
||||
- **No Results**: Replaced 🔍 with `Icons.Search`
|
||||
|
||||
### 3. Updated Player Page (`app/player/page.tsx`)
|
||||
- **Back Button**: Replaced ← with `Icons.ChevronLeft`
|
||||
- **Empty Player**: Replaced 📺 with `Icons.TV`
|
||||
- **Year Badge**: Replaced 📅 with `Icons.Calendar`
|
||||
- **Area Badge**: Replaced 🌍 with `Icons.Globe`
|
||||
- **Episode List Title**: Replaced 📑 with `Icons.List`
|
||||
- **Playing Indicator**: Replaced ▶️ with `Icons.Play`
|
||||
- **Empty Episodes**: Replaced 📭 with `Icons.Inbox`
|
||||
|
||||
### 4. Updated Layout (`app/layout.tsx`)
|
||||
- Added explicit favicon configuration to metadata
|
||||
|
||||
## Design Principles Applied
|
||||
|
||||
All icons follow the Liquid Glass design system:
|
||||
|
||||
1. **Consistent Stroke**: All icons use 2px stroke width
|
||||
2. **Round Caps**: strokeLinecap="round" for smooth, soft edges
|
||||
3. **Round Joins**: strokeLinejoin="round" for continuous flow
|
||||
4. **Scalable**: Size prop allows flexible sizing while maintaining proportions
|
||||
5. **Color Aware**: Uses currentColor to inherit text color
|
||||
6. **Accessible**: Clear, recognizable shapes with good contrast
|
||||
|
||||
## Icon Usage Example
|
||||
|
||||
```tsx
|
||||
import { Icons } from '@/components/ui/Icon';
|
||||
|
||||
// Basic usage
|
||||
<Icons.Film />
|
||||
|
||||
// With custom size
|
||||
<Icons.Search size={20} />
|
||||
|
||||
// With styling
|
||||
<Icons.Calendar size={14} className="mr-1 text-blue-500" />
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Consistent Visual Language**: All icons now match the Liquid Glass aesthetic
|
||||
2. **Better Scalability**: SVG icons scale perfectly at any size
|
||||
3. **Improved Accessibility**: Proper semantic icons instead of decorative emoji
|
||||
4. **Theme Support**: Icons adapt to light/dark mode through currentColor
|
||||
5. **Performance**: SVG icons load faster and render crisper than emoji
|
||||
6. **Maintainability**: Centralized icon system makes updates easier
|
||||
|
||||
## Files Modified
|
||||
|
||||
1. ✅ `components/ui/Icon.tsx` - Created
|
||||
2. ✅ `app/page.tsx` - Updated all icons
|
||||
3. ✅ `app/player/page.tsx` - Updated all icons
|
||||
4. ✅ `app/layout.tsx` - Added favicon config
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
- [ ] Logo displays correctly in navbar
|
||||
- [ ] Search icon shows in button
|
||||
- [ ] All feature cards display correct icons
|
||||
- [ ] Empty states show appropriate icons
|
||||
- [ ] Player page icons render properly
|
||||
- [ ] Episode list icons work correctly
|
||||
- [ ] All icons scale properly on different screen sizes
|
||||
- [ ] Dark mode displays icons correctly
|
||||
- [ ] Icons maintain consistent style across all pages
|
||||
@@ -1,399 +0,0 @@
|
||||
# KVideo Platform - Implementation Guide
|
||||
|
||||
## Overview
|
||||
|
||||
KVideo is a Next.js-based video aggregation platform that fetches content from multiple third-party APIs, provides intelligent source switching, and implements advanced M3U8 ad filtering for seamless video playback.
|
||||
|
||||
## Architecture
|
||||
|
||||
### 1. Core Type System (`lib/types/`)
|
||||
|
||||
**Purpose**: Centralized TypeScript type definitions for the entire application.
|
||||
|
||||
**Key Types**:
|
||||
- `VideoSource`: Configuration for third-party API sources
|
||||
- `VideoItem`: Search result structure
|
||||
- `VideoDetail`: Full video information with episodes
|
||||
- `PlayerState`: Current playback state
|
||||
- `VideoHistoryItem`: Viewing history with progress
|
||||
- `ApiResponse`: Standardized API response formats
|
||||
|
||||
### 2. API Layer
|
||||
|
||||
#### `lib/api/video-sources.ts`
|
||||
**Manages video source configuration**:
|
||||
- Stores multiple API endpoints with headers
|
||||
- Validates source configurations
|
||||
- Health checks for source availability
|
||||
- Custom source management via localStorage
|
||||
- Priority-based source ordering
|
||||
|
||||
**Key Functions**:
|
||||
- `getAllSources()`: Get all available sources
|
||||
- `getEnabledSources()`: Get enabled sources sorted by priority
|
||||
- `healthCheckSource(source)`: Test source availability and response time
|
||||
- `addCustomSource(source)`: Add user-defined API sources
|
||||
|
||||
#### `lib/api/client.ts`
|
||||
**HTTP client for video data fetching**:
|
||||
- Parallel requests to multiple sources
|
||||
- 15-second timeout with abort controller
|
||||
- 3-attempt retry mechanism with exponential backoff
|
||||
- Response normalization across different API formats
|
||||
- M3U8 URL extraction from various formats
|
||||
|
||||
**Key Functions**:
|
||||
- `searchVideos(query, sources, page)`: Search across multiple sources
|
||||
- `getVideoDetail(id, source)`: Fetch video details with episodes
|
||||
- `testVideoUrl(url)`: Check video URL accessibility
|
||||
- `normalizeVideoData(data, sourceId)`: Standardize API responses
|
||||
|
||||
### 3. Server API Routes
|
||||
|
||||
#### `app/api/search/route.ts`
|
||||
**Handles video search requests**:
|
||||
- POST and GET endpoints
|
||||
- Validates query and source parameters
|
||||
- Aggregates results from multiple sources
|
||||
- Returns merged results with source attribution
|
||||
|
||||
**Request Format**:
|
||||
```json
|
||||
{
|
||||
"query": "search term",
|
||||
"sources": ["source_1", "source_2"],
|
||||
"page": 1
|
||||
}
|
||||
```
|
||||
|
||||
**Response Format**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"query": "search term",
|
||||
"page": 1,
|
||||
"sources": [
|
||||
{
|
||||
"results": [...],
|
||||
"source": "source_1",
|
||||
"responseTime": 234
|
||||
}
|
||||
],
|
||||
"totalResults": 42
|
||||
}
|
||||
```
|
||||
|
||||
#### `app/api/detail/route.ts`
|
||||
**Fetches video details**:
|
||||
- GET and POST endpoints
|
||||
- Extracts episode lists and M3U8 URLs
|
||||
- Supports custom API URLs
|
||||
- Returns structured video data with episodes
|
||||
|
||||
**Query Parameters**:
|
||||
- `id`: Video ID
|
||||
- `source`: Source identifier
|
||||
- `customApi`: (Optional) Custom API URL
|
||||
|
||||
### 4. State Management
|
||||
|
||||
#### `lib/store/player-store.ts` (Zustand)
|
||||
**Manages video playback state**:
|
||||
```typescript
|
||||
State: {
|
||||
currentVideo: { id, title, url, source, episodeIndex }
|
||||
episodes: Episode[]
|
||||
playbackPosition: number
|
||||
duration: number
|
||||
isPlaying: boolean
|
||||
autoplayNext: boolean
|
||||
volume: number (0-1)
|
||||
playbackRate: number
|
||||
}
|
||||
|
||||
Actions: {
|
||||
setVideo(video)
|
||||
updatePosition(position)
|
||||
nextEpisode() // Returns next episode or null
|
||||
prevEpisode() // Returns previous episode or null
|
||||
toggleAutoplay()
|
||||
setVolume(volume)
|
||||
setPlaybackRate(rate)
|
||||
}
|
||||
```
|
||||
|
||||
**Persistence**: Saves volume, playback rate, and autoplay settings to localStorage.
|
||||
|
||||
#### `lib/store/history-store.ts` (Zustand)
|
||||
**Manages viewing history**:
|
||||
- Stores last 50 watched videos
|
||||
- Deduplicates by show identifier
|
||||
- Updates progress and timestamp
|
||||
- Moves recently watched to top
|
||||
- Persists to localStorage
|
||||
|
||||
**Key Functions**:
|
||||
- `addToHistory(...)`: Add or update history entry
|
||||
- `updateProgress(videoId, source, episodeIndex, position, duration)`
|
||||
- `getHistoryItem(videoId, source)`: Retrieve specific history entry
|
||||
- `clearHistory()`: Clear all history
|
||||
|
||||
### 5. Utility Modules
|
||||
|
||||
#### `lib/utils/progress-tracker.ts`
|
||||
**LocalStorage-based progress management**:
|
||||
- Auto-saves progress every 5 seconds (throttled)
|
||||
- Skips if position < 10s or video almost finished (< 2min remaining)
|
||||
- Clears progress when video completes
|
||||
- Provides resume position on reload
|
||||
- Auto-cleans entries older than 30 days
|
||||
|
||||
**Key Functions**:
|
||||
- `saveProgress(videoId, source, position, duration, episodeIndex)`
|
||||
- `getProgress(videoId, source)`: Returns stored progress or null
|
||||
- `shouldResumeProgress(progress)`: Check if position is valid for resume
|
||||
- `createProgressSaver(interval)`: Returns throttled save function
|
||||
|
||||
#### `lib/utils/error-handler.ts`
|
||||
**Comprehensive error handling**:
|
||||
- Categorizes errors: NETWORK, MEDIA, HLS, API, TIMEOUT
|
||||
- HLS.js error recovery strategies:
|
||||
- `networkError`: Retry with `hls.startLoad()`
|
||||
- `mediaError`: Call `hls.recoverMediaError()`
|
||||
- `bufferAppendError`: Ignore if playback started
|
||||
- `fatal`: Destroy and recreate player
|
||||
- Exponential backoff retry logic
|
||||
- User-friendly error messages
|
||||
|
||||
**Key Functions**:
|
||||
- `handleHLSError(hls, errorData, retryCount)`: Returns recovery action
|
||||
- `retryWithBackoff(fn, maxRetries, initialDelay)`
|
||||
- `isRetryableError(error)`: Check if error can be retried
|
||||
- `ErrorRecovery.recoverNetwork(retryFn, maxAttempts)`
|
||||
|
||||
#### `lib/utils/search.ts`
|
||||
**Search optimization utilities**:
|
||||
- Debounce search input (500ms default)
|
||||
- Merge and deduplicate results from multiple sources
|
||||
- Normalize titles for comparison
|
||||
- Filter by year, area, type, keyword
|
||||
- Sort by relevance, year, name, or update time
|
||||
- Search history management (max 20 entries)
|
||||
|
||||
**Key Functions**:
|
||||
- `debounce(func, delay)`: Debounce function calls
|
||||
- `mergeSearchResults(results)`: Deduplicate and merge
|
||||
- `filterResults(results, filters)`: Apply search filters
|
||||
- `sortResults(results, sortBy)`: Sort by criteria
|
||||
- `saveSearchQuery(query)`: Save to history
|
||||
|
||||
#### `lib/utils/episode-manager.ts`
|
||||
**Episode navigation logic**:
|
||||
- Builds player URLs with episode parameters
|
||||
- Parses URL query parameters
|
||||
- Validates episode indices
|
||||
- Groups episodes into sections (20 per section)
|
||||
- Supports episode order toggle (normal/reversed)
|
||||
- Formats episode names and tracks progress
|
||||
|
||||
**Key Functions**:
|
||||
- `buildPlayerUrl(params)`: Create player URL with episode info
|
||||
- `parsePlayerParams(searchParams)`: Extract episode params from URL
|
||||
- `getNextEpisodeParams(currentParams, episodes)`: Get next episode
|
||||
- `groupEpisodesIntoSections(episodes, sectionSize)`: Paginate episodes
|
||||
- `toggleEpisodeOrder()`: Switch between normal/reversed order
|
||||
|
||||
#### `lib/utils/source-switcher.ts`
|
||||
**Multi-source speed testing**:
|
||||
- Tests all sources in parallel
|
||||
- Measures API response time + video URL accessibility
|
||||
- Sorts by: current source → speed (fast to slow) → errors
|
||||
- Speed indicators: <1000ms=Fast, <2000ms=Medium, >2000ms=Slow
|
||||
- Caches test results for 5 minutes
|
||||
- Recommends switch if alternative is 50%+ faster
|
||||
|
||||
**Key Functions**:
|
||||
- `testAllSources(videoTitle, sources, currentSource)`: Test all sources
|
||||
- `getSpeedIndicator(speed)`: Return color-coded speed level
|
||||
- `findBestSource(results)`: Get fastest available source
|
||||
- `shouldSwitchSource(current, best)`: Check if switch is beneficial
|
||||
- `buildSourceSwitchUrl(...)`: Create URL with new source
|
||||
|
||||
#### `lib/utils/m3u8-filter.ts`
|
||||
**Ad filtering for M3U8 playlists**:
|
||||
- Custom HLS loader extending HLS.js
|
||||
- Intercepts M3U8 manifest requests
|
||||
- Parses playlist line-by-line
|
||||
- Filters segments containing ad patterns:
|
||||
- `/ad/`, `/ads/`, `/advertisement/`, `_ad_`, `-ad-`
|
||||
- Keywords: 'commercial', 'sponsored', 'promo'
|
||||
- Removes discontinuity tags around filtered segments
|
||||
- Preserves valid video segments
|
||||
|
||||
**Key Classes/Functions**:
|
||||
- `AdFilteringHLSLoader`: Custom HLS loader class
|
||||
- `filterM3U8Playlist(content, baseUrl)`: Remove ad segments
|
||||
- `createAdFilteringConfig(hlsConfig)`: Create HLS config with filtering
|
||||
- `detectAdsInM3U8(url)`: Analyze playlist for ads
|
||||
- `addCustomAdPattern(pattern)`: Add user-defined ad patterns
|
||||
|
||||
## Data Flow
|
||||
|
||||
### 1. Search Flow
|
||||
```
|
||||
User Input → Debounce (500ms) → API Route (/api/search)
|
||||
→ Parallel requests to sources → Normalize responses
|
||||
→ Merge & deduplicate → Display results
|
||||
```
|
||||
|
||||
### 2. Video Selection Flow
|
||||
```
|
||||
User clicks video → Navigate to detail page → API Route (/api/detail)
|
||||
→ Fetch video details → Extract episodes → Parse M3U8 URLs
|
||||
→ Initialize player store → Navigate to player page
|
||||
```
|
||||
|
||||
### 3. Playback Flow
|
||||
```
|
||||
Player page loads → Create HLS instance with AdFilteringLoader
|
||||
→ Load M3U8 URL → Filter ads → Initialize Artplayer
|
||||
→ Resume from saved position (if valid)
|
||||
→ Auto-save progress every 5s
|
||||
→ On video end: Clear progress, auto-play next if enabled
|
||||
```
|
||||
|
||||
### 4. Source Switching Flow
|
||||
```
|
||||
User clicks "Switch Source" → Search video title across all sources
|
||||
→ Test each source speed (parallel):
|
||||
- Fetch detail API
|
||||
- HEAD request to first episode URL
|
||||
- Calculate response time
|
||||
→ Sort by speed → Display with color indicators
|
||||
→ User selects source → Navigate to new URL with updated params
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### HLS Errors
|
||||
- **Network Error**: Retry with `hls.startLoad()` (max 3 attempts)
|
||||
- **Media Error**: Call `hls.recoverMediaError()` (max 3 attempts)
|
||||
- **Buffer Stalled**: Restart loading
|
||||
- **Fatal Error**: Destroy player and suggest alternative source
|
||||
|
||||
### API Errors
|
||||
- **Timeout**: Retry with exponential backoff
|
||||
- **404/500**: Mark source as unavailable
|
||||
- **Network Failure**: Show user-friendly message, suggest alternative
|
||||
|
||||
### Recovery Strategies
|
||||
1. Auto-retry with exponential backoff (1s, 2s, 4s)
|
||||
2. Switch to alternative source if current fails
|
||||
3. Resume from last saved position after recovery
|
||||
4. Clear corrupted localStorage data and reset
|
||||
|
||||
## Configuration
|
||||
|
||||
### Adding Custom Sources
|
||||
```typescript
|
||||
import { addCustomSource } from '@/lib/api/video-sources';
|
||||
|
||||
addCustomSource({
|
||||
id: 'custom_source',
|
||||
name: 'My Custom API',
|
||||
baseUrl: 'https://api.example.com',
|
||||
searchPath: '/api.php/provide/vod',
|
||||
detailPath: '/api.php/provide/vod',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0' },
|
||||
enabled: true,
|
||||
priority: 3
|
||||
});
|
||||
```
|
||||
|
||||
### Customizing Ad Filters
|
||||
```typescript
|
||||
import { addCustomAdPattern } from '@/lib/utils/m3u8-filter';
|
||||
|
||||
addCustomAdPattern('/custom-ad-path/');
|
||||
```
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
1. **Parallel API Requests**: Fetch from all sources simultaneously
|
||||
2. **Request Timeout**: 15s timeout prevents hanging requests
|
||||
3. **Result Caching**: Speed test results cached for 5 minutes
|
||||
4. **Throttled Progress Saving**: Auto-save limited to every 5 seconds
|
||||
5. **Lazy Loading**: Episodes loaded only when needed
|
||||
6. **Ad Filtering**: Reduces bandwidth and loading time
|
||||
7. **Source Priority**: Faster sources prioritized automatically
|
||||
|
||||
## Local Storage Keys
|
||||
|
||||
- `kvideo_custom_sources`: Custom API sources
|
||||
- `kvideo-player-store`: Player settings (volume, rate, autoplay)
|
||||
- `kvideo-history-store`: Viewing history
|
||||
- `kvideo_progress_{source}_{videoId}`: Video progress
|
||||
- `kvideo_search_history`: Search query history
|
||||
- `kvideo_speed_test_cache`: Source speed test cache
|
||||
- `kvideo_episode_order`: Episode order preference
|
||||
- `kvideo_custom_ad_patterns`: Custom ad filter patterns
|
||||
|
||||
## API Compatibility
|
||||
|
||||
The platform expects third-party APIs to return JSON in this format:
|
||||
|
||||
### Search Response
|
||||
```json
|
||||
{
|
||||
"code": 1,
|
||||
"list": [
|
||||
{
|
||||
"vod_id": 123,
|
||||
"vod_name": "Video Title",
|
||||
"vod_pic": "https://...",
|
||||
"type_name": "Movie",
|
||||
"vod_remarks": "HD",
|
||||
"vod_year": "2024"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Detail Response
|
||||
```json
|
||||
{
|
||||
"code": 1,
|
||||
"list": [
|
||||
{
|
||||
"vod_id": 123,
|
||||
"vod_name": "Video Title",
|
||||
"vod_pic": "https://...",
|
||||
"vod_play_url": "Episode1$url1#Episode2$url2",
|
||||
"vod_play_from": "m3u8"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Install Dependencies**:
|
||||
```bash
|
||||
npm install zustand hls.js artplayer
|
||||
```
|
||||
|
||||
2. **Configure API Sources**: Edit `lib/api/video-sources.ts` with real API endpoints
|
||||
|
||||
3. **Build UI Components**: Create React components using the logic layers
|
||||
|
||||
4. **Add Player Component**: Integrate HLS.js and Artplayer with the stores
|
||||
|
||||
5. **Test Error Recovery**: Simulate network failures and verify recovery
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- Never expose API keys in client-side code
|
||||
- Validate all user inputs before API requests
|
||||
- Sanitize video URLs before loading
|
||||
- Implement rate limiting on API routes
|
||||
- Use CORS properly for third-party API calls
|
||||
@@ -1,36 +1,311 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
# KVideo
|
||||
|
||||
> A modern, elegant video streaming platform with intelligent source aggregation
|
||||
|
||||
[](https://nextjs.org/)
|
||||
[](https://reactjs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://tailwindcss.com/)
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [About The Project](#about-the-project)
|
||||
- [Built With](#built-with)
|
||||
- [Key Features](#key-features)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Installation](#installation)
|
||||
- [Usage](#usage)
|
||||
- [Development Server](#development-server)
|
||||
- [Production Build](#production-build)
|
||||
- [Architecture](#architecture)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Core Components](#core-components)
|
||||
- [Design System](#design-system)
|
||||
- [Contributing](#contributing)
|
||||
- [License](#license)
|
||||
- [Contact](#contact)
|
||||
|
||||
## About The Project
|
||||
|
||||
KVideo is a sophisticated video streaming platform that intelligently aggregates content from multiple video sources, providing users with a seamless, unified viewing experience. Built with modern web technologies and designed with the "Liquid Glass" design philosophy, KVideo offers an elegant, intuitive interface that adapts beautifully to both light and dark modes.
|
||||
|
||||
The platform features intelligent source checking, automatic failover, playback history tracking, and a fully responsive design that works flawlessly across all devices.
|
||||
|
||||
### Built With
|
||||
|
||||
KVideo is built using cutting-edge web technologies:
|
||||
|
||||
- **[Next.js 16](https://nextjs.org/)** - React framework with App Router
|
||||
- **[React 19](https://reactjs.org/)** - UI library with modern hooks
|
||||
- **[TypeScript](https://www.typescriptlang.org/)** - Type-safe development
|
||||
- **[Tailwind CSS 4](https://tailwindcss.com/)** - Utility-first styling
|
||||
- **[Artplayer](https://artplayer.org/)** - Advanced HTML5 video player
|
||||
- **[HLS.js](https://github.com/video-dev/hls.js/)** - HLS streaming support
|
||||
- **[Zustand](https://github.com/pmndrs/zustand)** - Lightweight state management
|
||||
|
||||
### Key Features
|
||||
|
||||
#### 🎯 **Intelligent Multi-Source Aggregation**
|
||||
- Automatically searches across multiple video sources
|
||||
- Smart source validation and availability checking
|
||||
- Real-time source health monitoring
|
||||
- Automatic failover to working sources
|
||||
|
||||
#### 🎨 **Modern "Liquid Glass" UI**
|
||||
- Beautiful glassmorphism design system
|
||||
- Smooth animations and transitions
|
||||
- Comprehensive component library
|
||||
- Dark/Light theme support with system detection
|
||||
|
||||
#### 🎬 **Advanced Video Player**
|
||||
- HLS streaming support
|
||||
- Episode management and auto-play
|
||||
- Playback progress tracking
|
||||
- Customizable playback controls
|
||||
- Picture-in-Picture support
|
||||
|
||||
#### 📚 **Smart History Management**
|
||||
- Automatic playback position saving
|
||||
- Intelligent show deduplication
|
||||
- Cross-device history sync
|
||||
- Episode progress tracking
|
||||
|
||||
#### 🔍 **Enhanced Search Experience**
|
||||
- Real-time search results
|
||||
- Search result caching (10-minute duration)
|
||||
- Loading animations with progress indicators
|
||||
- Source availability badges
|
||||
|
||||
#### 📱 **Fully Responsive**
|
||||
- Mobile-first design approach
|
||||
- Optimized for all screen sizes
|
||||
- Touch-friendly interface
|
||||
- Progressive Web App ready
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
Follow these steps to get KVideo running on your local machine.
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
### Prerequisites
|
||||
|
||||
Ensure you have the following installed:
|
||||
|
||||
- **Node.js** (v18.0.0 or higher)
|
||||
- **npm** (v9.0.0 or higher) or **yarn** (v1.22.0 or higher)
|
||||
|
||||
```sh
|
||||
# Check your Node.js version
|
||||
node --version
|
||||
|
||||
# Check your npm version
|
||||
npm --version
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
### Installation
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
1. **Clone the repository**
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
```sh
|
||||
git clone https://github.com/KuekHaoYang/Video.git
|
||||
cd kvideo
|
||||
```
|
||||
|
||||
## Learn More
|
||||
2. **Install dependencies**
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
3. **Set up environment variables (optional)**
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
Create a `.env.local` file in the root directory if you need to configure custom settings:
|
||||
|
||||
## Deploy on Vercel
|
||||
```env
|
||||
# Add any environment-specific configuration here
|
||||
NEXT_PUBLIC_API_URL=your_api_url
|
||||
```
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
4. **Run the development server**
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
5. **Open your browser**
|
||||
|
||||
Navigate to [http://localhost:3000](http://localhost:3000) to see the application running.
|
||||
|
||||
## Usage
|
||||
|
||||
### Development Server
|
||||
|
||||
Start the development server with hot-reload:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The application will be available at `http://localhost:3000`.
|
||||
|
||||
### Production Build
|
||||
|
||||
Build the application for production:
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
|
||||
Start the production server:
|
||||
|
||||
```sh
|
||||
npm start
|
||||
```
|
||||
|
||||
### Linting
|
||||
|
||||
Run ESLint to check code quality:
|
||||
|
||||
```sh
|
||||
npm run lint
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
kvideo/
|
||||
├── app/ # Next.js App Router
|
||||
│ ├── api/ # API routes
|
||||
│ │ ├── detail/ # Video detail endpoint
|
||||
│ │ ├── search/ # Search endpoint
|
||||
│ │ └── search-stream/ # Streaming search endpoint
|
||||
│ ├── player/ # Video player page
|
||||
│ ├── layout.tsx # Root layout
|
||||
│ ├── page.tsx # Home page
|
||||
│ └── globals.css # Global styles
|
||||
├── components/ # React components
|
||||
│ ├── ui/ # UI component library
|
||||
│ │ ├── Badge.tsx
|
||||
│ │ ├── Button.tsx
|
||||
│ │ ├── Card.tsx
|
||||
│ │ ├── Icon.tsx
|
||||
│ │ └── Input.tsx
|
||||
│ ├── SearchLoadingAnimation.tsx
|
||||
│ ├── ThemeProvider.tsx
|
||||
│ └── ThemeSwitcher.tsx
|
||||
├── lib/ # Core utilities
|
||||
│ ├── api/ # API client
|
||||
│ │ ├── client.ts
|
||||
│ │ └── video-sources.ts
|
||||
│ ├── store/ # State management
|
||||
│ │ ├── history-store.ts
|
||||
│ │ └── player-store.ts
|
||||
│ ├── types/ # TypeScript definitions
|
||||
│ │ └── index.ts
|
||||
│ └── utils/ # Utility functions
|
||||
│ ├── episode-manager.ts
|
||||
│ ├── error-handler.ts
|
||||
│ ├── m3u8-filter.ts
|
||||
│ ├── progress-tracker.ts
|
||||
│ ├── search.ts
|
||||
│ ├── source-checker.ts
|
||||
│ ├── source-switcher.ts
|
||||
│ └── url-validator.ts
|
||||
├── public/ # Static assets
|
||||
├── next.config.ts # Next.js configuration
|
||||
├── tailwind.config.ts # Tailwind configuration
|
||||
├── tsconfig.json # TypeScript configuration
|
||||
└── package.json # Project dependencies
|
||||
```
|
||||
|
||||
### Core Components
|
||||
|
||||
#### **Search System**
|
||||
- **Multi-source Search**: Parallel queries across multiple video APIs
|
||||
- **Result Caching**: 10-minute cache to reduce API calls
|
||||
- **Progress Tracking**: Real-time feedback on search and validation progress
|
||||
|
||||
#### **Video Player**
|
||||
- **Episode Management**: Sequential episode navigation with auto-play
|
||||
- **Progress Tracking**: Automatic position saving and restoration
|
||||
- **Source Switching**: Seamless failover between video sources
|
||||
- **HLS Support**: Adaptive bitrate streaming
|
||||
|
||||
#### **State Management**
|
||||
- **Player Store**: Manages playback state, episodes, and settings
|
||||
- **History Store**: Tracks viewing history with smart deduplication
|
||||
|
||||
#### **API Layer**
|
||||
- **Client Abstraction**: Unified interface for multiple video sources
|
||||
- **Error Handling**: Graceful degradation and retry logic
|
||||
- **Source Validation**: Health checks and availability monitoring
|
||||
|
||||
## Design System
|
||||
|
||||
KVideo implements the **"Liquid Glass"** design system, featuring:
|
||||
|
||||
### Visual Principles
|
||||
|
||||
- **Glass Effect**: Sophisticated backdrop-filter with frosted translucency
|
||||
- **Universal Softness**: Consistent rounded corners (`rounded-2xl` and `rounded-full`)
|
||||
- **Fluid Animations**: Physics-based transitions with cubic-bezier curves
|
||||
- **Depth & Layering**: Clear z-axis hierarchy with natural shadows
|
||||
- **Adaptive Controls**: Dynamic elements that respond to user interaction
|
||||
|
||||
### Component Library
|
||||
|
||||
The UI component library includes:
|
||||
- Avatar & Badge
|
||||
- Buttons (primary, secondary, disabled states)
|
||||
- Cards with glass morphism
|
||||
- Form inputs with validation
|
||||
- Modals & Drawers
|
||||
- Tabs & Navigation
|
||||
- Progress indicators
|
||||
- Theme switcher with system detection
|
||||
|
||||
### Typography & Accessibility
|
||||
|
||||
- **Font**: San Francisco (SF) system font stack
|
||||
- **Contrast**: WCAG 2.2 compliant (minimum 4.5:1 ratio)
|
||||
- **Semantic HTML**: Proper HTML5 structure
|
||||
- **ARIA Support**: Comprehensive ARIA attributes
|
||||
- **Keyboard Navigation**: Full keyboard operability
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
|
||||
|
||||
### How to Contribute
|
||||
|
||||
1. **Fork the Project**
|
||||
2. **Create your Feature Branch** (`git checkout -b feature/AmazingFeature`)
|
||||
3. **Commit your Changes** (`git commit -m 'Add some AmazingFeature'`)
|
||||
4. **Push to the Branch** (`git push origin feature/AmazingFeature`)
|
||||
5. **Open a Pull Request**
|
||||
|
||||
### Development Guidelines
|
||||
|
||||
- Follow the existing code style and conventions
|
||||
- Write meaningful commit messages
|
||||
- Add tests for new features
|
||||
- Update documentation as needed
|
||||
- Ensure all tests pass before submitting
|
||||
|
||||
## License
|
||||
|
||||
This project is private and not currently licensed for public use.
|
||||
|
||||
## Contact
|
||||
|
||||
**Hao Yang Kuek** - [@KuekHaoYang](https://github.com/KuekHaoYang)
|
||||
|
||||
Project Link: [https://github.com/KuekHaoYang/Video](https://github.com/KuekHaoYang/Video)
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<sub>Built with ❤️ using Next.js and the Liquid Glass design system</sub>
|
||||
</p>
|
||||
|
||||
-215
@@ -1,215 +0,0 @@
|
||||
# KVideo - Video Aggregation Platform
|
||||
|
||||
A Next.js-based video streaming platform that aggregates content from multiple third-party APIs with intelligent source switching and advanced ad filtering.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- 🔍 **Multi-Source Search**: Search across multiple video APIs simultaneously
|
||||
- ⚡ **Intelligent Source Switching**: Automatic speed testing and source recommendation
|
||||
- 🎯 **Advanced Ad Filtering**: M3U8 playlist ad segment removal
|
||||
- 💾 **Progress Tracking**: Auto-save and resume from last watched position
|
||||
- 📱 **Episode Management**: Smart episode navigation with progress tracking
|
||||
- 🔄 **Error Recovery**: Automatic retry and fallback mechanisms
|
||||
- 📊 **Viewing History**: Track last 50 watched videos
|
||||
- ⚙️ **Custom Sources**: Add your own video API endpoints
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+ and npm
|
||||
- Modern browser with LocalStorage support
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Or run setup script
|
||||
chmod +x setup.sh
|
||||
./setup.sh
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
Edit `lib/api/video-sources.ts` with your video API endpoints:
|
||||
|
||||
```typescript
|
||||
export const DEFAULT_SOURCES: VideoSource[] = [
|
||||
{
|
||||
id: 'source_1',
|
||||
name: 'Primary Video API',
|
||||
baseUrl: 'https://your-api.com',
|
||||
searchPath: '/api.php/provide/vod',
|
||||
detailPath: '/api.php/provide/vod',
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Visit [http://localhost:3000](http://localhost:3000)
|
||||
|
||||
### Production
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
- **[SETUP.md](SETUP.md)** - Detailed setup instructions and examples
|
||||
- **[IMPLEMENTATION.md](IMPLEMENTATION.md)** - Architecture and API documentation
|
||||
- **[SUMMARY.md](SUMMARY.md)** - Implementation overview
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
```
|
||||
KVideo Platform
|
||||
├── API Layer (Multi-source aggregation)
|
||||
├── State Management (Zustand stores)
|
||||
├── Utility Layer (Search, Progress, Episodes)
|
||||
├── Error Handling (Recovery strategies)
|
||||
└── M3U8 Ad Filtering (Custom HLS loader)
|
||||
```
|
||||
|
||||
### Core Components
|
||||
|
||||
#### API Layer
|
||||
- **video-sources.ts**: Source configuration and health checks
|
||||
- **client.ts**: HTTP client with retry logic and timeouts
|
||||
- **search/route.ts**: Search API endpoint
|
||||
- **detail/route.ts**: Video detail API endpoint
|
||||
|
||||
#### State Management
|
||||
- **player-store.ts**: Video playback state (Zustand)
|
||||
- **history-store.ts**: Viewing history (Zustand)
|
||||
|
||||
#### Utilities
|
||||
- **progress-tracker.ts**: LocalStorage-based progress management
|
||||
- **error-handler.ts**: Comprehensive error recovery
|
||||
- **search.ts**: Search optimization and debouncing
|
||||
- **episode-manager.ts**: Episode navigation logic
|
||||
- **source-switcher.ts**: Speed testing and source comparison
|
||||
- **m3u8-filter.ts**: Ad filtering for HLS streams
|
||||
|
||||
## 🎯 Key Features Explained
|
||||
|
||||
### Multi-Source Aggregation
|
||||
Search across multiple video APIs simultaneously with parallel requests, automatic deduplication, and response time tracking.
|
||||
|
||||
### Intelligent Source Switching
|
||||
- Tests all available sources in parallel
|
||||
- Measures API response time + video URL accessibility
|
||||
- Provides visual speed indicators (Fast/Medium/Slow)
|
||||
- Recommends faster alternatives
|
||||
- Caches results for 5 minutes
|
||||
|
||||
### Advanced Ad Filtering
|
||||
Custom HLS loader that:
|
||||
- Intercepts M3U8 playlist requests
|
||||
- Filters segments containing ad patterns
|
||||
- Removes discontinuity tags
|
||||
- Preserves valid video segments
|
||||
- Supports custom ad pattern rules
|
||||
|
||||
### Progress Tracking
|
||||
- Auto-saves progress every 5 seconds (throttled)
|
||||
- Resumes from last position on reload
|
||||
- Clears progress when video finishes
|
||||
- Per-episode progress tracking
|
||||
- Auto-cleanup of old entries
|
||||
|
||||
## 🔧 Configuration
|
||||
|
||||
### Timeouts & Limits
|
||||
|
||||
```typescript
|
||||
// lib/api/client.ts
|
||||
const REQUEST_TIMEOUT = 15000; // 15 seconds
|
||||
const MAX_RETRIES = 3; // 3 attempts
|
||||
|
||||
// lib/utils/progress-tracker.ts
|
||||
const PROGRESS_SAVE_THRESHOLD = 10; // Skip if < 10s
|
||||
const RESUME_MIN_POSITION = 10; // Resume if > 10s
|
||||
```
|
||||
|
||||
### Custom Ad Patterns
|
||||
|
||||
```typescript
|
||||
import { addCustomAdPattern } from '@/lib/utils/m3u8-filter';
|
||||
addCustomAdPattern('/your-ad-path/');
|
||||
```
|
||||
|
||||
## 📖 API Usage
|
||||
|
||||
### Search Videos
|
||||
|
||||
```bash
|
||||
POST /api/search
|
||||
{
|
||||
"query": "movie name",
|
||||
"sources": ["source_1", "source_2"],
|
||||
"page": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Get Video Detail
|
||||
|
||||
```bash
|
||||
GET /api/detail?id=123&source=source_1
|
||||
```
|
||||
|
||||
## 🛠️ Tech Stack
|
||||
|
||||
- **Next.js 16** - React framework
|
||||
- **TypeScript** - Type safety
|
||||
- **Zustand** - State management
|
||||
- **HLS.js** - Video streaming
|
||||
- **Artplayer** - Video player UI
|
||||
|
||||
## 📦 Dependencies
|
||||
|
||||
```json
|
||||
{
|
||||
"zustand": "^5.0.2",
|
||||
"hls.js": "^1.5.15",
|
||||
"artplayer": "^5.1.7"
|
||||
}
|
||||
```
|
||||
|
||||
## 🎨 UI Components Needed
|
||||
|
||||
To complete the platform, create these components:
|
||||
|
||||
- SearchBar with debouncing
|
||||
- VideoGrid for search results
|
||||
- VideoPlayer with HLS.js integration
|
||||
- EpisodeList with navigation
|
||||
- SourceSwitcher with speed indicators
|
||||
- HistoryList with progress bars
|
||||
|
||||
## 📄 License
|
||||
|
||||
MIT License
|
||||
|
||||
## 📞 Support
|
||||
|
||||
For detailed documentation:
|
||||
- Check `IMPLEMENTATION.md` for architecture
|
||||
- Review `SETUP.md` for setup instructions
|
||||
- See `SUMMARY.md` for overview
|
||||
|
||||
---
|
||||
|
||||
**Status**: Core logic implementation complete ✅
|
||||
**Next Steps**: Build UI components and integrate with logic layers
|
||||
|
||||
Built with ❤️ using Next.js and TypeScript
|
||||
@@ -1,368 +0,0 @@
|
||||
# KVideo Platform - Setup Guide
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Install Dependencies
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
This will install:
|
||||
- **zustand** (v5.0.2): State management
|
||||
- **hls.js** (v1.5.15): HLS video streaming
|
||||
- **artplayer** (v5.1.7): Video player UI
|
||||
|
||||
### 2. Configure Video Sources
|
||||
|
||||
Edit `lib/api/video-sources.ts` and update the `DEFAULT_SOURCES` array with your video API endpoints:
|
||||
|
||||
```typescript
|
||||
export const DEFAULT_SOURCES: VideoSource[] = [
|
||||
{
|
||||
id: 'source_1',
|
||||
name: 'Primary Video API',
|
||||
baseUrl: 'https://your-api-domain.com',
|
||||
searchPath: '/api.php/provide/vod',
|
||||
detailPath: '/api.php/provide/vod',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0',
|
||||
},
|
||||
enabled: true,
|
||||
priority: 1,
|
||||
},
|
||||
// Add more sources...
|
||||
];
|
||||
```
|
||||
|
||||
### 3. Run Development Server
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Visit `http://localhost:3000`
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
kvideo/
|
||||
├── app/
|
||||
│ ├── api/
|
||||
│ │ ├── search/route.ts # Search API endpoint
|
||||
│ │ └── detail/route.ts # Detail API endpoint
|
||||
│ ├── globals.css
|
||||
│ ├── layout.tsx
|
||||
│ └── page.tsx
|
||||
├── lib/
|
||||
│ ├── types/
|
||||
│ │ └── index.ts # TypeScript type definitions
|
||||
│ ├── api/
|
||||
│ │ ├── video-sources.ts # Source configuration
|
||||
│ │ └── client.ts # HTTP client
|
||||
│ ├── store/
|
||||
│ │ ├── player-store.ts # Player state (Zustand)
|
||||
│ │ └── history-store.ts # History state (Zustand)
|
||||
│ └── utils/
|
||||
│ ├── progress-tracker.ts # Progress management
|
||||
│ ├── error-handler.ts # Error handling
|
||||
│ ├── search.ts # Search utilities
|
||||
│ ├── episode-manager.ts # Episode navigation
|
||||
│ ├── source-switcher.ts # Source testing
|
||||
│ └── m3u8-filter.ts # Ad filtering
|
||||
├── components/
|
||||
│ └── player/
|
||||
│ └── VideoPlayer.tsx # (To be created)
|
||||
├── IMPLEMENTATION.md # Detailed architecture guide
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## Core Functionality
|
||||
|
||||
### 1. Multi-Source Video Search
|
||||
|
||||
```typescript
|
||||
// Example: Search across multiple sources
|
||||
import { searchVideos } from '@/lib/api/client';
|
||||
import { getEnabledSources } from '@/lib/api/video-sources';
|
||||
|
||||
const sources = getEnabledSources();
|
||||
const results = await searchVideos('movie name', sources, 1);
|
||||
|
||||
// Results include response time and source attribution
|
||||
results.forEach(result => {
|
||||
console.log(`Source: ${result.source}`);
|
||||
console.log(`Response time: ${result.responseTime}ms`);
|
||||
console.log(`Results: ${result.results.length}`);
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Video Player State Management
|
||||
|
||||
```typescript
|
||||
// Example: Using player store
|
||||
import { usePlayerStore } from '@/lib/store/player-store';
|
||||
|
||||
function VideoPlayer() {
|
||||
const { currentVideo, episodes, nextEpisode } = usePlayerStore();
|
||||
|
||||
const handleVideoEnd = () => {
|
||||
const next = nextEpisode();
|
||||
if (next) {
|
||||
console.log('Auto-playing next episode:', next.name);
|
||||
}
|
||||
};
|
||||
|
||||
// Player component logic...
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Progress Tracking
|
||||
|
||||
```typescript
|
||||
// Example: Save and restore progress
|
||||
import { saveProgress, getProgress, shouldResumeProgress } from '@/lib/utils/progress-tracker';
|
||||
|
||||
// Save progress every 5 seconds
|
||||
const handleTimeUpdate = (currentTime: number) => {
|
||||
saveProgress(videoId, source, currentTime, duration, episodeIndex);
|
||||
};
|
||||
|
||||
// Resume on load
|
||||
const storedProgress = getProgress(videoId, source);
|
||||
if (shouldResumeProgress(storedProgress)) {
|
||||
player.currentTime = storedProgress.position;
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Source Speed Testing
|
||||
|
||||
```typescript
|
||||
// Example: Test and switch sources
|
||||
import { testAllSources, getSpeedIndicator } from '@/lib/utils/source-switcher';
|
||||
|
||||
const results = await testAllSources(videoTitle, sources, currentSource);
|
||||
|
||||
results.forEach(result => {
|
||||
const indicator = getSpeedIndicator(result.speed);
|
||||
console.log(`${result.sourceName}: ${indicator.label} (${result.speed}ms)`);
|
||||
});
|
||||
|
||||
// Get fastest source
|
||||
const fastest = results.find(r => r.available);
|
||||
```
|
||||
|
||||
### 5. M3U8 Ad Filtering
|
||||
|
||||
```typescript
|
||||
// Example: Initialize HLS with ad filtering
|
||||
import Hls from 'hls.js';
|
||||
import { createAdFilteringConfig } from '@/lib/utils/m3u8-filter';
|
||||
|
||||
const hls = new Hls(createAdFilteringConfig());
|
||||
hls.loadSource(m3u8Url);
|
||||
hls.attachMedia(videoElement);
|
||||
```
|
||||
|
||||
## API Usage
|
||||
|
||||
### Search Endpoint
|
||||
|
||||
**POST** `/api/search`
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"query": "movie name",
|
||||
"sources": ["source_1", "source_2"],
|
||||
"page": 1
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"query": "movie name",
|
||||
"page": 1,
|
||||
"sources": [
|
||||
{
|
||||
"results": [...],
|
||||
"source": "source_1",
|
||||
"responseTime": 234
|
||||
}
|
||||
],
|
||||
"totalResults": 42
|
||||
}
|
||||
```
|
||||
|
||||
### Detail Endpoint
|
||||
|
||||
**GET** `/api/detail?id=123&source=source_1`
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"vod_id": 123,
|
||||
"vod_name": "Movie Title",
|
||||
"vod_pic": "https://...",
|
||||
"episodes": [
|
||||
{
|
||||
"name": "Episode 1",
|
||||
"url": "https://...",
|
||||
"index": 0
|
||||
}
|
||||
],
|
||||
"source": "source_1"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Create `.env.local`:
|
||||
|
||||
```bash
|
||||
# Optional: Default video sources
|
||||
NEXT_PUBLIC_DEFAULT_SOURCE_1=https://api.example1.com
|
||||
NEXT_PUBLIC_DEFAULT_SOURCE_2=https://api.example2.com
|
||||
|
||||
# Optional: Analytics
|
||||
NEXT_PUBLIC_GA_ID=your-google-analytics-id
|
||||
|
||||
# Development
|
||||
NODE_ENV=development
|
||||
```
|
||||
|
||||
## Building for Production
|
||||
|
||||
```bash
|
||||
# Build the application
|
||||
npm run build
|
||||
|
||||
# Start production server
|
||||
npm start
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Test API Sources
|
||||
|
||||
```bash
|
||||
# Use the health check function
|
||||
node -e "
|
||||
const { healthCheckSources, getAllSources } = require('./lib/api/video-sources');
|
||||
const sources = getAllSources();
|
||||
healthCheckSources(sources).then(results => {
|
||||
results.forEach((result, sourceId) => {
|
||||
console.log(sourceId, result);
|
||||
});
|
||||
});
|
||||
"
|
||||
```
|
||||
|
||||
### Test Search Functionality
|
||||
|
||||
```bash
|
||||
# Test search via API route
|
||||
curl -X POST http://localhost:3000/api/search \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"query":"test","sources":["source_1"],"page":1}'
|
||||
```
|
||||
|
||||
### Test Detail Fetch
|
||||
|
||||
```bash
|
||||
# Test detail via API route
|
||||
curl "http://localhost:3000/api/detail?id=123&source=source_1"
|
||||
```
|
||||
|
||||
## Common Issues
|
||||
|
||||
### 1. HLS.js Not Loading
|
||||
|
||||
**Solution**: Ensure the video URL is a valid M3U8 playlist and CORS is enabled on the video server.
|
||||
|
||||
```typescript
|
||||
// Add CORS headers in next.config.ts if needed
|
||||
const nextConfig = {
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: '/api/:path*',
|
||||
headers: [
|
||||
{ key: 'Access-Control-Allow-Origin', value: '*' },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 2. LocalStorage Quota Exceeded
|
||||
|
||||
**Solution**: The app auto-cleans old progress entries. You can also manually clear:
|
||||
|
||||
```typescript
|
||||
import { clearOldProgress } from '@/lib/utils/progress-tracker';
|
||||
clearOldProgress(30); // Clear entries older than 30 days
|
||||
```
|
||||
|
||||
### 3. Source Timeout
|
||||
|
||||
**Solution**: Adjust timeout in `lib/api/client.ts`:
|
||||
|
||||
```typescript
|
||||
const REQUEST_TIMEOUT = 15000; // Increase if needed
|
||||
```
|
||||
|
||||
### 4. Ad Filtering Not Working
|
||||
|
||||
**Solution**: Add custom patterns:
|
||||
|
||||
```typescript
|
||||
import { addCustomAdPattern } from '@/lib/utils/m3u8-filter';
|
||||
addCustomAdPattern('/your-ad-path/');
|
||||
```
|
||||
|
||||
## Browser Compatibility
|
||||
|
||||
- ✅ Chrome 90+
|
||||
- ✅ Firefox 88+
|
||||
- ✅ Safari 14+
|
||||
- ✅ Edge 90+
|
||||
|
||||
**Requirements**:
|
||||
- LocalStorage support
|
||||
- Fetch API
|
||||
- ES6+ JavaScript
|
||||
|
||||
## Performance Tips
|
||||
|
||||
1. **Limit Concurrent Sources**: Test with 3-5 sources max for optimal speed
|
||||
2. **Enable Caching**: Speed test results cached for 5 minutes
|
||||
3. **Throttle Progress**: Auto-save limited to every 5 seconds
|
||||
4. **Lazy Load Episodes**: Only fetch episodes when needed
|
||||
5. **Use CDN**: Serve static assets via CDN for faster loading
|
||||
|
||||
## Contributing
|
||||
|
||||
See `IMPLEMENTATION.md` for detailed architecture documentation.
|
||||
|
||||
## License
|
||||
|
||||
MIT License - See LICENSE file for details
|
||||
|
||||
## Support
|
||||
|
||||
For issues and questions:
|
||||
1. Check `IMPLEMENTATION.md` for detailed documentation
|
||||
2. Review error logs in browser console
|
||||
3. Test API sources with health check function
|
||||
4. Verify CORS configuration on video servers
|
||||
|
||||
---
|
||||
|
||||
**Next Steps**: Create UI components and integrate with the logic layers! All the core business logic is now implemented and ready to use.
|
||||
-282
@@ -1,282 +0,0 @@
|
||||
# KVideo Platform - Implementation Summary
|
||||
|
||||
## ✅ Completed Implementation
|
||||
|
||||
All core business logic for the KVideo video aggregation platform has been successfully implemented. Below is a comprehensive overview of what was built.
|
||||
|
||||
## 📦 Files Created
|
||||
|
||||
### Type Definitions
|
||||
- ✅ `lib/types/index.ts` - Complete TypeScript type system
|
||||
|
||||
### API Layer
|
||||
- ✅ `lib/api/video-sources.ts` - Source management with health checks
|
||||
- ✅ `lib/api/client.ts` - HTTP client with retry logic
|
||||
- ✅ `app/api/search/route.ts` - Search API endpoint
|
||||
- ✅ `app/api/detail/route.ts` - Detail API endpoint
|
||||
|
||||
### State Management
|
||||
- ✅ `lib/store/player-store.ts` - Player state (Zustand)
|
||||
- ✅ `lib/store/history-store.ts` - History state (Zustand)
|
||||
|
||||
### Utilities
|
||||
- ✅ `lib/utils/progress-tracker.ts` - Progress persistence
|
||||
- ✅ `lib/utils/error-handler.ts` - Error recovery
|
||||
- ✅ `lib/utils/search.ts` - Search optimization
|
||||
- ✅ `lib/utils/episode-manager.ts` - Episode navigation
|
||||
- ✅ `lib/utils/source-switcher.ts` - Source speed testing
|
||||
- ✅ `lib/utils/m3u8-filter.ts` - Ad filtering
|
||||
|
||||
### Documentation
|
||||
- ✅ `IMPLEMENTATION.md` - Architecture guide
|
||||
- ✅ `SETUP.md` - Setup instructions
|
||||
- ✅ `package.json` - Updated with dependencies
|
||||
|
||||
## 🎯 Key Features Implemented
|
||||
|
||||
### 1. Multi-Source Video Aggregation
|
||||
- Parallel API requests to multiple sources
|
||||
- Response time tracking and source prioritization
|
||||
- Automatic result deduplication
|
||||
- Custom source configuration via localStorage
|
||||
|
||||
### 2. Intelligent Source Switching
|
||||
- Parallel speed testing across all sources
|
||||
- Response time measurement (API + video URL test)
|
||||
- Visual speed indicators (Fast/Medium/Slow)
|
||||
- Automatic recommendation for faster sources
|
||||
- 5-minute result caching
|
||||
|
||||
### 3. Advanced M3U8 Ad Filtering
|
||||
- Custom HLS loader with ad detection
|
||||
- Pattern-based filtering (/ad/, /ads/, _ad_, etc.)
|
||||
- Keyword filtering (commercial, sponsored, promo)
|
||||
- Custom pattern support
|
||||
- Automatic discontinuity tag handling
|
||||
|
||||
### 4. Progress Tracking System
|
||||
- Auto-save every 5 seconds (throttled)
|
||||
- Resume from last position
|
||||
- Smart save logic (skip if < 10s or almost finished)
|
||||
- Auto-cleanup of old entries (30+ days)
|
||||
- Per-episode progress tracking
|
||||
|
||||
### 5. State Management
|
||||
- Zustand stores for player and history
|
||||
- localStorage persistence
|
||||
- Optimized re-renders with selector hooks
|
||||
- Max 50 history items with deduplication
|
||||
|
||||
### 6. Error Handling & Recovery
|
||||
- HLS.js error categorization and recovery
|
||||
- Exponential backoff retry mechanism
|
||||
- Network error recovery strategies
|
||||
- User-friendly error messages
|
||||
- Automatic source failover
|
||||
|
||||
### 7. Search Optimization
|
||||
- 500ms debounce for search input
|
||||
- Result merging from multiple sources
|
||||
- Search history (max 20 entries)
|
||||
- Filtering by year, area, type, keyword
|
||||
- Sorting by relevance, year, name, update
|
||||
|
||||
### 8. Episode Management
|
||||
- URL parameter building and parsing
|
||||
- Next/previous episode navigation
|
||||
- Episode grouping (20 per section)
|
||||
- Order toggle (normal/reversed)
|
||||
- Episode progress tracking
|
||||
|
||||
## 🔄 Data Flow Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ USER INTERFACE │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ STATE MANAGEMENT │
|
||||
│ ┌──────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Player Store │ │ History Store │ │
|
||||
│ │ (Zustand) │ │ (Zustand) │ │
|
||||
│ └──────────────────┘ └──────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ UTILITY LAYER │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Progress │ │ Episode │ │ Source │ │
|
||||
│ │ Tracker │ │ Manager │ │ Switcher │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Error │ │ Search │ │ M3U8 │ │
|
||||
│ │ Handler │ │ Utils │ │ Filter │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ API LAYER │
|
||||
│ ┌──────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Video Sources │ │ API Client │ │
|
||||
│ │ Configuration │ │ (HTTP + Retry) │ │
|
||||
│ └──────────────────┘ └──────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ SERVER API ROUTES │
|
||||
│ /api/search /api/detail │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ THIRD-PARTY VIDEO APIS │
|
||||
│ Source 1 Source 2 Source 3 Custom Sources │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 🎬 Typical User Flow
|
||||
|
||||
### Search & Play Flow
|
||||
1. User types search query → Debounced (500ms)
|
||||
2. POST to `/api/search` with selected sources
|
||||
3. Parallel requests to all sources with timeout
|
||||
4. Results normalized, merged, deduplicated
|
||||
5. User selects video → Navigate to detail
|
||||
6. GET `/api/detail?id=X&source=Y`
|
||||
7. Extract episodes and M3U8 URLs
|
||||
8. Initialize player with HLS + ad filtering
|
||||
9. Check for saved progress → Resume if valid
|
||||
10. Start playback → Auto-save progress every 5s
|
||||
11. On video end → Check autoplay → Load next episode
|
||||
|
||||
### Source Switching Flow
|
||||
1. User clicks "Switch Source" button
|
||||
2. Search video title across all enabled sources
|
||||
3. Parallel speed tests:
|
||||
- Fetch detail API
|
||||
- HEAD request to first episode URL
|
||||
- Calculate total response time
|
||||
4. Sort results: current first → by speed → errors last
|
||||
5. Display with color indicators (green/yellow/red)
|
||||
6. User selects faster source
|
||||
7. Navigate to new URL with updated params
|
||||
8. Keep same episode index if available
|
||||
|
||||
## 📊 Performance Characteristics
|
||||
|
||||
- **Search Speed**: Parallel requests complete in ~2-5 seconds
|
||||
- **Progress Save**: Throttled to every 5 seconds
|
||||
- **Source Test**: 10-second timeout per source
|
||||
- **Request Timeout**: 15 seconds with 3 retries
|
||||
- **History Limit**: 50 items max
|
||||
- **Cache Duration**: 5 minutes for speed tests
|
||||
|
||||
## 🔧 Configuration Points
|
||||
|
||||
### Video Sources (`lib/api/video-sources.ts`)
|
||||
```typescript
|
||||
export const DEFAULT_SOURCES: VideoSource[] = [
|
||||
{
|
||||
id: 'source_1',
|
||||
name: 'Primary API',
|
||||
baseUrl: 'https://api.example.com',
|
||||
searchPath: '/api.php/provide/vod',
|
||||
detailPath: '/api.php/provide/vod',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0' },
|
||||
enabled: true,
|
||||
priority: 1,
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
### Timeouts & Limits (`lib/api/client.ts`)
|
||||
```typescript
|
||||
const REQUEST_TIMEOUT = 15000; // 15 seconds
|
||||
const MAX_RETRIES = 3; // 3 attempts
|
||||
const RETRY_DELAY = 1000; // 1 second base
|
||||
```
|
||||
|
||||
### Progress Settings (`lib/utils/progress-tracker.ts`)
|
||||
```typescript
|
||||
const PROGRESS_SAVE_THRESHOLD = 10; // Skip if < 10s
|
||||
const RESUME_MIN_POSITION = 10; // Resume if > 10s
|
||||
const RESUME_MAX_REMAINING = 120; // Skip if < 2min left
|
||||
```
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
### Required:
|
||||
1. **Install Dependencies**: Run `npm install`
|
||||
2. **Configure Sources**: Update API endpoints in `video-sources.ts`
|
||||
3. **Build UI Components**: Create React components using the logic
|
||||
4. **Integrate Player**: Use HLS.js + Artplayer with the stores
|
||||
|
||||
### Optional:
|
||||
5. Add authentication system
|
||||
6. Implement user favorites/bookmarks
|
||||
7. Add subtitle support
|
||||
8. Create admin panel for source management
|
||||
9. Add analytics and tracking
|
||||
10. Implement PWA features
|
||||
|
||||
## 🧪 Testing Checklist
|
||||
|
||||
- [ ] Test API source health checks
|
||||
- [ ] Verify search across multiple sources
|
||||
- [ ] Test video detail fetching
|
||||
- [ ] Verify progress save/restore
|
||||
- [ ] Test source speed comparison
|
||||
- [ ] Verify M3U8 ad filtering
|
||||
- [ ] Test error recovery mechanisms
|
||||
- [ ] Verify localStorage persistence
|
||||
- [ ] Test episode navigation
|
||||
- [ ] Cross-browser compatibility
|
||||
|
||||
## 📝 Code Quality
|
||||
|
||||
- ✅ Full TypeScript type safety
|
||||
- ✅ Comprehensive error handling
|
||||
- ✅ Modular architecture
|
||||
- ✅ Separation of concerns
|
||||
- ✅ No business logic in components
|
||||
- ✅ Reusable utility functions
|
||||
- ✅ LocalStorage management
|
||||
- ✅ Performance optimizations
|
||||
|
||||
## 🎨 UI Components Needed
|
||||
|
||||
To complete the platform, you'll need to create:
|
||||
|
||||
1. **SearchBar** - Uses search utils with debouncing
|
||||
2. **VideoGrid** - Displays search results
|
||||
3. **VideoCard** - Shows video info with poster
|
||||
4. **VideoPlayer** - Integrates HLS.js + Artplayer
|
||||
5. **EpisodeList** - Episode selection UI
|
||||
6. **SourceSwitcher** - Speed test results display
|
||||
7. **HistoryList** - Viewing history display
|
||||
8. **ProgressBar** - Visual progress indicator
|
||||
9. **ErrorBoundary** - Error display and retry
|
||||
10. **SettingsPanel** - Source and filter configuration
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
- **IMPLEMENTATION.md**: Detailed architecture and API docs
|
||||
- **SETUP.md**: Setup instructions and examples
|
||||
- **README.md**: (Update with project overview)
|
||||
|
||||
## 🎉 Summary
|
||||
|
||||
All core business logic for the KVideo platform has been implemented with:
|
||||
- ✅ 14 source files created
|
||||
- ✅ 13 utility functions
|
||||
- ✅ 2 Zustand stores
|
||||
- ✅ 2 API routes
|
||||
- ✅ Complete type system
|
||||
- ✅ Comprehensive documentation
|
||||
|
||||
The platform is now ready for UI integration!
|
||||
@@ -1,279 +0,0 @@
|
||||
# KVideo - Remaining Tasks Checklist
|
||||
|
||||
## ✅ Completed (Core Logic Implementation)
|
||||
|
||||
- [x] TypeScript type definitions
|
||||
- [x] API source configuration and management
|
||||
- [x] HTTP client with retry logic
|
||||
- [x] Search API endpoint
|
||||
- [x] Detail API endpoint
|
||||
- [x] Player state store (Zustand)
|
||||
- [x] History state store (Zustand)
|
||||
- [x] Progress tracking utilities
|
||||
- [x] Error handling utilities
|
||||
- [x] Search optimization utilities
|
||||
- [x] Episode management utilities
|
||||
- [x] Source switching utilities
|
||||
- [x] M3U8 ad filtering utilities
|
||||
- [x] Comprehensive documentation
|
||||
|
||||
## 🎯 Next Steps (UI Implementation)
|
||||
|
||||
### Phase 1: Setup & Configuration
|
||||
- [ ] Run `npm install` to install dependencies
|
||||
- [ ] Update `lib/api/video-sources.ts` with real API endpoints
|
||||
- [ ] Test API sources with health check
|
||||
- [ ] Verify API routes work correctly
|
||||
|
||||
### Phase 2: Core UI Components
|
||||
|
||||
#### Search Components
|
||||
- [ ] Create `components/search/SearchBar.tsx`
|
||||
- Integrate debounce from `lib/utils/search.ts`
|
||||
- Use search history
|
||||
- Implement autocomplete
|
||||
|
||||
- [ ] Create `components/search/VideoGrid.tsx`
|
||||
- Display search results
|
||||
- Show source badges
|
||||
- Implement infinite scroll or pagination
|
||||
|
||||
- [ ] Create `components/search/VideoCard.tsx`
|
||||
- Show video poster, title, year, type
|
||||
- Display video metadata
|
||||
- Click handler to navigate to player
|
||||
|
||||
- [ ] Create `components/search/SearchFilters.tsx`
|
||||
- Filter by year, area, type
|
||||
- Sort options (relevance, year, name)
|
||||
|
||||
#### Player Components
|
||||
- [ ] Create `components/player/VideoPlayer.tsx`
|
||||
- Initialize HLS.js with `createAdFilteringConfig()`
|
||||
- Integrate Artplayer
|
||||
- Connect to `usePlayerStore`
|
||||
- Implement progress saving with `createProgressSaver()`
|
||||
- Handle HLS errors with `handleHLSError()`
|
||||
- Auto-resume from `getProgress()`
|
||||
- Auto-play next episode when enabled
|
||||
|
||||
- [ ] Create `components/player/PlayerControls.tsx`
|
||||
- Play/pause button
|
||||
- Volume control
|
||||
- Playback rate selector
|
||||
- Fullscreen toggle
|
||||
- Progress bar
|
||||
|
||||
- [ ] Create `components/player/EpisodeList.tsx`
|
||||
- Display episodes with `useEpisodes()`
|
||||
- Highlight current episode
|
||||
- Use `buildPlayerUrl()` for navigation
|
||||
- Show watched progress
|
||||
- Support episode order toggle
|
||||
|
||||
- [ ] Create `components/player/SourceSwitcher.tsx`
|
||||
- Button to trigger source test
|
||||
- Display `testAllSources()` results
|
||||
- Show speed indicators with colors
|
||||
- Handle source selection
|
||||
- Use `buildSourceSwitchUrl()`
|
||||
|
||||
#### History & Extras
|
||||
- [ ] Create `components/history/HistoryList.tsx`
|
||||
- Display `useViewingHistory()`
|
||||
- Show progress bars
|
||||
- Resume playback button
|
||||
- Delete history item option
|
||||
|
||||
- [ ] Create `components/common/ErrorBoundary.tsx`
|
||||
- Catch React errors
|
||||
- Display user-friendly messages
|
||||
- Retry button
|
||||
|
||||
- [ ] Create `components/common/LoadingSpinner.tsx`
|
||||
- Show during API requests
|
||||
- Skeleton loaders for cards
|
||||
|
||||
### Phase 3: Pages
|
||||
|
||||
- [ ] Create/Update `app/page.tsx` (Home/Search page)
|
||||
- SearchBar component
|
||||
- VideoGrid component
|
||||
- SearchFilters component
|
||||
|
||||
- [ ] Create `app/player/page.tsx`
|
||||
- VideoPlayer component
|
||||
- EpisodeList component
|
||||
- SourceSwitcher component
|
||||
- Parse URL params with `parsePlayerParams()`
|
||||
|
||||
- [ ] Create `app/history/page.tsx`
|
||||
- HistoryList component
|
||||
- Clear history button
|
||||
|
||||
- [ ] Create `app/settings/page.tsx` (Optional)
|
||||
- Custom source management
|
||||
- Ad pattern configuration
|
||||
- Autoplay settings
|
||||
- Clear cache options
|
||||
|
||||
### Phase 4: Integration & Testing
|
||||
|
||||
- [ ] Connect SearchBar to `/api/search`
|
||||
- [ ] Connect VideoPlayer to `/api/detail`
|
||||
- [ ] Test progress save/restore flow
|
||||
- [ ] Test source switching functionality
|
||||
- [ ] Test error recovery mechanisms
|
||||
- [ ] Test episode navigation
|
||||
- [ ] Test history tracking
|
||||
- [ ] Cross-browser testing
|
||||
|
||||
### Phase 5: Styling (Using Liquid Glass Design System)
|
||||
|
||||
- [ ] Apply Liquid Glass styles to all components
|
||||
- Use `rounded-2xl` for containers
|
||||
- Use `rounded-full` for avatars/badges/buttons
|
||||
- Implement glass effect with `backdrop-filter`
|
||||
- Add smooth animations
|
||||
- Ensure dark mode support
|
||||
|
||||
- [ ] Responsive design
|
||||
- Mobile-first approach
|
||||
- Breakpoints for tablet/desktop
|
||||
- Touch-friendly controls
|
||||
|
||||
### Phase 6: Enhancements (Optional)
|
||||
|
||||
- [ ] Add keyboard shortcuts for player
|
||||
- [ ] Implement picture-in-picture mode
|
||||
- [ ] Add subtitle support
|
||||
- [ ] Implement video quality selection
|
||||
- [ ] Add favorites/bookmarks feature
|
||||
- [ ] Implement watch later queue
|
||||
- [ ] Add share functionality
|
||||
- [ ] PWA support (offline mode)
|
||||
- [ ] Add analytics tracking
|
||||
|
||||
### Phase 7: Deployment
|
||||
|
||||
- [ ] Configure environment variables
|
||||
- [ ] Set up production build
|
||||
- [ ] Optimize images and assets
|
||||
- [ ] Enable compression
|
||||
- [ ] Configure caching headers
|
||||
- [ ] Deploy to Vercel/Netlify
|
||||
- [ ] Set up monitoring and error tracking
|
||||
- [ ] Performance testing
|
||||
|
||||
## 📝 Example Code Templates
|
||||
|
||||
### SearchBar Integration
|
||||
```typescript
|
||||
import { debounce } from '@/lib/utils/search';
|
||||
import { useState } from 'react';
|
||||
|
||||
const handleSearch = debounce(async (query: string) => {
|
||||
const response = await fetch('/api/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ query, sources: ['source_1'] }),
|
||||
});
|
||||
const data = await response.json();
|
||||
setResults(data.sources.flatMap(s => s.results));
|
||||
}, 500);
|
||||
```
|
||||
|
||||
### VideoPlayer Integration
|
||||
```typescript
|
||||
import Hls from 'hls.js';
|
||||
import { createAdFilteringConfig } from '@/lib/utils/m3u8-filter';
|
||||
import { usePlayerStore } from '@/lib/store/player-store';
|
||||
import { createProgressSaver } from '@/lib/utils/progress-tracker';
|
||||
|
||||
const { currentVideo } = usePlayerStore();
|
||||
const saveProgress = createProgressSaver();
|
||||
|
||||
useEffect(() => {
|
||||
const hls = new Hls(createAdFilteringConfig());
|
||||
hls.loadSource(currentVideo.url);
|
||||
hls.attachMedia(videoRef.current);
|
||||
|
||||
videoRef.current.addEventListener('timeupdate', () => {
|
||||
saveProgress(
|
||||
currentVideo.id,
|
||||
currentVideo.source,
|
||||
videoRef.current.currentTime,
|
||||
videoRef.current.duration,
|
||||
currentVideo.episodeIndex
|
||||
);
|
||||
});
|
||||
}, [currentVideo]);
|
||||
```
|
||||
|
||||
### Source Switcher Integration
|
||||
```typescript
|
||||
import { testAllSources, getSpeedIndicator } from '@/lib/utils/source-switcher';
|
||||
import { getEnabledSources } from '@/lib/api/video-sources';
|
||||
|
||||
const handleSwitchSource = async () => {
|
||||
const sources = getEnabledSources();
|
||||
const results = await testAllSources(videoTitle, sources, currentSource);
|
||||
|
||||
results.forEach(result => {
|
||||
const indicator = getSpeedIndicator(result.speed);
|
||||
// Display with color: indicator.color
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
## 🎯 Priority Order
|
||||
|
||||
1. **High Priority** (Core Functionality)
|
||||
- SearchBar, VideoGrid, VideoCard
|
||||
- VideoPlayer with HLS integration
|
||||
- Basic EpisodeList
|
||||
- Progress tracking
|
||||
|
||||
2. **Medium Priority** (Enhanced UX)
|
||||
- SourceSwitcher
|
||||
- HistoryList
|
||||
- Error handling UI
|
||||
- PlayerControls
|
||||
|
||||
3. **Low Priority** (Nice to Have)
|
||||
- Settings page
|
||||
- Advanced filters
|
||||
- PWA features
|
||||
- Analytics
|
||||
|
||||
## 📊 Estimated Time
|
||||
|
||||
- Phase 1: Setup - 30 minutes
|
||||
- Phase 2: Components - 8-12 hours
|
||||
- Phase 3: Pages - 2-4 hours
|
||||
- Phase 4: Integration - 2-4 hours
|
||||
- Phase 5: Styling - 4-6 hours
|
||||
- Phase 6: Enhancements - Variable
|
||||
- Phase 7: Deployment - 2-3 hours
|
||||
|
||||
**Total Core Implementation**: ~20-30 hours
|
||||
|
||||
## 🔍 Testing Checklist
|
||||
|
||||
- [ ] Search returns results from multiple sources
|
||||
- [ ] Video plays with ad filtering
|
||||
- [ ] Progress saves and restores correctly
|
||||
- [ ] Source switching tests and switches sources
|
||||
- [ ] Episode navigation works
|
||||
- [ ] History tracks correctly
|
||||
- [ ] Errors recover gracefully
|
||||
- [ ] Works on mobile/tablet/desktop
|
||||
- [ ] Dark mode works
|
||||
- [ ] LocalStorage persists across sessions
|
||||
|
||||
---
|
||||
|
||||
**Current Status**: All business logic implemented ✅
|
||||
**Ready for**: UI component development
|
||||
|
||||
Good luck building the UI! 🚀
|
||||
Reference in New Issue
Block a user