diff --git a/ICON_UPDATE_SUMMARY.md b/ICON_UPDATE_SUMMARY.md
deleted file mode 100644
index 416811c..0000000
--- a/ICON_UPDATE_SUMMARY.md
+++ /dev/null
@@ -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
-
+ Built with โค๏ธ using Next.js and the Liquid Glass design system +
diff --git a/README_NEW.md b/README_NEW.md deleted file mode 100644 index 5e47bfd..0000000 --- a/README_NEW.md +++ /dev/null @@ -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 diff --git a/SETUP.md b/SETUP.md deleted file mode 100644 index bd11c56..0000000 --- a/SETUP.md +++ /dev/null @@ -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. diff --git a/SUMMARY.md b/SUMMARY.md deleted file mode 100644 index a4b8025..0000000 --- a/SUMMARY.md +++ /dev/null @@ -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! diff --git a/TODO.md b/TODO.md deleted file mode 100644 index f2c6cba..0000000 --- a/TODO.md +++ /dev/null @@ -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! ๐