# StreamFlow IPTV - Architecture Overview

## System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                         Client Layer                         │
│  ┌──────────────────────────────────────────────────────┐  │
│  │    React Frontend (Port 12345)                       │  │
│  │    - Material-UI Components                          │  │
│  │    - React Router (SPA)                              │  │
│  │    - Zustand State Management                        │  │
│  │    - i18next (EN/RO)                                 │  │
│  │    - Light/Dark Theme                                │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                              │
                              ↓ HTTPS/API Calls
┌─────────────────────────────────────────────────────────────┐
│                         API Layer                            │
│  ┌──────────────────────────────────────────────────────┐  │
│  │    Express.js Server (Node.js)                       │  │
│  │    - JWT Authentication                              │  │
│  │    - Rate Limiting                                   │  │
│  │    - Helmet Security                                 │  │
│  │    - CORS                                            │  │
│  │    - RESTful API Endpoints                           │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                              │
                              ↓ Database Queries
┌─────────────────────────────────────────────────────────────┐
│                      Data Layer                              │
│  ┌──────────────────────────────────────────────────────┐  │
│  │    SQLite Database                                   │  │
│  │    - Users & Profiles                                │  │
│  │    - Playlists & Channels                            │  │
│  │    - EPG Data                                        │  │
│  │    - Recordings                                      │  │
│  │    - Watch History & Favorites                       │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                              │
                              ↓ Background Jobs
┌─────────────────────────────────────────────────────────────┐
│                    Processing Layer                          │
│  ┌──────────────────────────────────────────────────────┐  │
│  │    Background Services (node-cron)                   │  │
│  │    - EPG Sync (Hourly)                               │  │
│  │    - Channel Health Check (6h)                       │  │
│  │    - Recording Scheduler (1min)                      │  │
│  │                                                       │  │
│  │    Media Processing                                  │  │
│  │    - FFmpeg (transcoding, recording)                 │  │
│  │    - Streamlink (stream extraction)                  │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

## Security Architecture

### Container Security
- **Non-root user**: Application runs as UID 1001 (not root)
- **No new privileges**: Security-opt prevents privilege escalation
- **Capability dropping**: ALL capabilities dropped, only essential added
- **Read-only where possible**: Minimizes attack surface
- **Health checks**: Automatic container health monitoring

### Application Security
- **JWT Authentication**: Secure token-based auth with expiry
- **Bcrypt Password Hashing**: Industry-standard password protection (10 rounds)
- **Rate Limiting**: Protection against brute force attacks
- **Helmet.js**: Security headers (CSP, XSS protection, etc.)
- **Input Validation**: Express-validator on all inputs
- **CORS**: Configured for secure cross-origin requests
- **SQL Injection Protection**: Parameterized queries

### File System Security
- **Strict permissions**: 755 for directories, 644 for files (NO 777)
- **Isolated volumes**: Data segregation
- **Secure file uploads**: Size limits, type validation, sanitization

## Component Details

### Frontend (React + Vite)

**Core Dependencies:**
- `react@18.2.0` - UI library
- `react-router-dom@6.21.1` - Routing
- `@mui/material@5.15.3` - UI components
- `zustand@4.4.7` - State management
- `i18next@23.7.16` - Internationalization
- `react-player@2.14.1` - Video playback
- `axios@1.6.5` - HTTP client

**Features:**
- Single Page Application (SPA)
- Code splitting for optimal performance
- Lazy loading of components
- Service Worker ready (PWA capability)
- Responsive design (mobile-first)

### Backend (Node.js + Express)

**Core Dependencies:**
- `express@4.18.2` - Web framework
- `sqlite3@5.1.6` - Database
- `jsonwebtoken@9.0.2` - JWT auth
- `bcryptjs@2.4.3` - Password hashing
- `helmet@7.1.0` - Security middleware
- `multer@1.4.5` - File uploads
- `node-cron@3.0.3` - Scheduled jobs
- `fluent-ffmpeg@2.1.2` - Media processing

**API Structure:**
```
/api
├── /auth          - Authentication (login, register, verify)
├── /playlists     - Playlist management (CRUD, upload)
├── /channels      - Channel listing and filtering
├── /epg           - Electronic Program Guide
├── /recordings    - Recording management
├── /profiles      - User profiles
├── /radio         - Radio channels
├── /groups        - Custom channel groups
├── /settings      - User settings
├── /stream        - Stream proxy and management
└── /stats         - Analytics and statistics
```

### Database Schema

**Tables:**
1. **users** - User accounts (auth, role)
2. **profiles** - Multi-user profiles per account
3. **playlists** - M3U playlist metadata
4. **channels** - Individual channel entries
5. **custom_groups** - User-created channel groups
6. **group_channels** - Many-to-many group/channel relation
7. **epg_data** - Electronic Program Guide data
8. **epg_sources** - EPG data sources
9. **recordings** - Scheduled and completed recordings
10. **watch_history** - Viewing history tracking
11. **favorites** - User favorite channels
12. **settings** - Key-value user settings
13. **api_tokens** - API access tokens
14. **logo_cache** - Channel logo cache

**Indexes:**
- Channel lookup optimization
- EPG time-based queries
- User-specific data retrieval
- Fast favorites and history access

## Data Flow

### User Authentication Flow
```
1. User submits credentials → POST /api/auth/login
2. Server validates against database
3. Password verified with bcrypt
4. JWT token generated and returned
5. Frontend stores token in localStorage
6. Token included in subsequent API requests
7. Middleware validates token on each request
```

### Channel Playback Flow
```
1. User selects channel → Channel component
2. Channel URL passed to VideoPlayer component
3. ReactPlayer handles stream playback
4. Watch history recorded to database
5. Continue playing in background on navigation (PiP)
```

### Playlist Import Flow
```
1. User uploads M3U file or provides URL
2. Backend validates file/URL
3. M3U parser extracts channel data
4. Channels inserted into database (batched)
5. Logo fetching scheduled (background)
6. Frontend notified of completion
7. Channels appear in UI
```

## Scalability Considerations

### Current Architecture (Single Instance)
- Suitable for: 1-100 concurrent users
- Storage: Local SQLite database
- Media processing: Single FFmpeg instance

### Future Scaling Options

**Horizontal Scaling:**
- Add load balancer (nginx, HAProxy)
- Multiple backend containers
- Shared database (PostgreSQL, MySQL)
- Redis for session management
- Distributed file storage (MinIO, S3)

**Performance Optimization:**
- CDN for static assets
- Stream caching and proxying
- Database connection pooling
- Channel health check optimization
- Lazy EPG loading

## Monitoring and Logging

### Application Logs
- **Location**: `/app/logs/`
- **Files**: 
  - `error.log` - Error-level logs
  - `combined.log` - All logs
- **Rotation**: Winston handles rotation (5MB, 5 files)

### Docker Logs
```bash
docker-compose logs -f streamflow
```

### Health Monitoring
- **Endpoint**: `GET /api/health`
- **Docker health check**: Every 30s
- **Response**: JSON with status and timestamp

## Environment Configuration

### Required Variables
- `PORT` - Application port (12345)
- `JWT_SECRET` - JWT signing key
- `SESSION_SECRET` - Session encryption key

### Optional Variables
- `NODE_ENV` - Environment (production/development)
- `DB_PATH` - Database file path
- `MAX_RECORDING_SIZE` - Recording size limit
- `EPG_UPDATE_INTERVAL` - EPG sync frequency
- `LOG_LEVEL` - Logging verbosity

## Deployment Options

### Docker (Recommended)
- Self-contained, reproducible builds
- Isolated environment
- Easy updates and rollbacks
- Resource limiting
- Health monitoring

### Manual Deployment
- Install Node.js 20+
- Install FFmpeg and Streamlink
- Configure system user (non-root)
- Set up systemd service
- Configure nginx reverse proxy

### Cloud Deployment
- **AWS**: ECS with Fargate
- **Google Cloud**: Cloud Run
- **Azure**: Container Instances
- **DigitalOcean**: App Platform or Droplet

## Technology Choices Rationale

**Why SQLite?**
- Zero configuration
- Embedded, no separate server
- Perfect for single-instance deployments
- Excellent performance for this use case
- Easy backups (single file)

**Why React + Material-UI?**
- Component-based architecture
- Large ecosystem
- Material Design = modern, familiar UI
- Excellent mobile support
- Accessibility built-in

**Why Docker?**
- Consistent environments
- Security through isolation
- Easy deployment
- Portability
- Resource control

**Why Node.js?**
- JavaScript ecosystem
- Async I/O perfect for streaming
- Large package ecosystem
- FFmpeg integration
- Fast development

## Future Enhancements

### Planned Features
- WebSocket for real-time updates
- Progressive Web App (PWA) support
- Mobile apps (React Native)
- Advanced analytics dashboard
- Multi-language EPG support
- Chromecast/AirPlay support
- Social features (watch parties)
- Content recommendations (ML)

### Technical Debt
- Add comprehensive unit tests
- Implement end-to-end testing
- Add API documentation (Swagger)
- Implement caching layer
- Add metrics collection (Prometheus)
- Implement CI/CD pipeline

---

**Document Version**: 1.0  
**Last Updated**: December 2025  
**Author**: StreamFlow Development Team
