Add download and subtitle services, enhance UI with continue watching and quality selector widgets

- Implemented DownloadService for managing download tasks, including start, pause, resume, and cancel functionalities.
- Created SubtitleService for handling subtitle tracks, parsing SRT and WebVTT formats, and downloading subtitles.
- Added ContinueWatchingWidget to display user's watch history with progress indicators.
- Developed QualitySelectorWidget for selecting video quality during playback, including auto quality adjustment.
- Introduced TrendingWidget and RecentlyAddedWidget to showcase trending and recently added content.
This commit is contained in:
GitHub Copilot committed 2026-03-26 10:34:18 +01:00
1 parent a9a1127d6b
commit 91eb1ce5a0
20 files changed
+6574 -1

No files matched your search

@@ -0,0 +1,244 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/models/playlist_config.dart';
import '../models/playlist.dart';
/// Represents a content recommendation
class Recommendation {
final Playlist item;
final RecommendationType type;
final double score;
final String reason;
Recommendation({
required this.item,
required this.type,
this.score = 0.0,
required this.reason,
});
}
enum RecommendationType {
continueWatching,
trending,
recentlyAdded,
similarContent,
topRated,
forYou,
}
class RecommendationService {
/// Get continue watching items based on watch history
static List<Recommendation> getContinueWatching(
Map<String, dynamic> watchHistory,
List<Playlist> allContent,
) {
final recommendations = <Recommendation>[];
for (final item in allContent) {
final historyKey = item.streamId.toString();
if (watchHistory.containsKey(historyKey)) {
final lastPosition = watchHistory[historyKey] as double? ?? 0.0;
// Only show if watched more than 5 seconds ago and less than 95% complete
if (lastPosition > 5 && lastPosition < 95) {
recommendations.add(Recommendation(
item: item,
type: RecommendationType.continueWatching,
score: 100.0 - lastPosition, // Score higher if recently started
reason: 'Continue watching from ${lastPosition.toStringAsFixed(0)}%',
));
}
}
}
// Sort by last watched (highest incomplete progress first)
recommendations.sort((a, b) => b.score.compareTo(a.score));
return recommendations.take(10).toList();
}
/// Get trending content based on view counts
static List<Recommendation> getTrending(
Map<String, int> viewCounts,
List<Playlist> allContent,
) {
final recommendations = <Recommendation>[];
for (final item in allContent) {
final views = viewCounts[item.streamId.toString()] ?? 0;
if (views > 0) {
recommendations.add(Recommendation(
item: item,
type: RecommendationType.trending,
score: views.toDouble(),
reason: '$views views - Trending now',
));
}
}
recommendations.sort((a, b) => b.score.compareTo(a.score));
return recommendations.take(10).toList();
}
/// Get recently added content
static List<Recommendation> getRecentlyAdded(List<Playlist> allContent) {
final recommendations = <Recommendation>[];
// Sort by added date (most recent first)
final sorted = [...allContent];
sorted.sort((a, b) {
final aDate = DateTime.tryParse(a.added ?? '') ?? DateTime(2000);
final bDate = DateTime.tryParse(b.added ?? '') ?? DateTime(2000);
return bDate.compareTo(aDate);
});
for (final item in sorted.take(20)) {
final daysAgo = DateTime.now()
.difference(DateTime.tryParse(item.added ?? '') ?? DateTime(2000))
.inDays;
recommendations.add(Recommendation(
item: item,
type: RecommendationType.recentlyAdded,
score: (20 - daysAgo).toDouble().clamp(0, 100),
reason: 'Added $daysAgo days ago',
));
}
return recommendations.take(10).toList();
}
/// Get personalized recommendations based on watch history
static List<Recommendation> getForYou(
Map<String, dynamic> watchHistory,
List<Playlist> allContent,
) {
final recommendations = <Recommendation>[];
// Collect watched categories
final watchedCategories = <String>{};
watchHistory.forEach((key, value) {
if (value is Map && value.containsKey('category')) {
watchedCategories.add(value['category'] as String);
}
});
// Recommend similar content
for (final item in allContent) {
if (watchedCategories.contains(item.categoryId)) {
recommendations.add(Recommendation(
item: item,
type: RecommendationType.forYou,
score: 75.0,
reason: 'Based on your interests',
));
}
}
// Add highly rated content
var ratedContent = [...allContent];
ratedContent.sort((a, b) {
final aRating = double.tryParse(a.rating ?? '0') ?? 0.0;
final bRating = double.tryParse(b.rating ?? '0') ?? 0.0;
return bRating.compareTo(aRating);
});
for (final item in ratedContent.where((i) {
final rating = double.tryParse(i.rating ?? '0') ?? 0.0;
return rating >= 7.5;
}).take(5)) {
recommendations.add(Recommendation(
item: item,
type: RecommendationType.topRated,
score: double.tryParse(item.rating ?? '0') ?? 0.0,
reason: 'Highly rated - ${item.rating}/10',
));
}
// Remove duplicates and limit
final seen = <int>{};
final unique = <Recommendation>[];
for (final rec in recommendations) {
if (!seen.contains(rec.item.streamId)) {
unique.add(rec);
seen.add(rec.item.streamId);
}
}
return unique.take(15).toList();
}
}
/// Provider for watch history
final watchHistoryProvider = StateNotifierProvider<
WatchHistoryNotifier,
Map<String, dynamic>>((ref) {
return WatchHistoryNotifier();
});
class WatchHistoryNotifier extends StateNotifier<Map<String, dynamic>> {
WatchHistoryNotifier() : super({});
void updateWatchTime(int streamId, double percentage) {
state = {
...state,
streamId.toString(): {
'percentage': percentage,
'timestamp': DateTime.now().toIso8601String(),
},
};
}
void clearHistory() {
state = {};
}
}
/// Provider for view counts/trending
final trendingProvider = StateNotifierProvider<
TrendingNotifier,
Map<String, int>>((ref) {
return TrendingNotifier();
});
class TrendingNotifier extends StateNotifier<Map<String, int>> {
TrendingNotifier() : super({});
void incrementViewCount(int streamId) {
final key = streamId.toString();
state = {
...state,
key: (state[key] ?? 0) + 1,
};
}
}
/// Provider for recommendations
final recommendationsProvider =
FutureProvider.family<List<Recommendation>, (Playlist, Map<String, dynamic>, Map<String, int>, List<Playlist>)>(
(ref, params) async {
final (playlist, watchHistory, trending, allContent) = params;
// Combine all recommendation types
final allRecommendations = <Recommendation>[
...RecommendationService.getContinueWatching(watchHistory, allContent),
...RecommendationService.getTrending(trending, allContent),
...RecommendationService.getRecentlyAdded(allContent),
...RecommendationService.getForYou(watchHistory, allContent),
];
// Deduplicate and score
final seen = <int>{};
final scored = <Recommendation>[];
for (final rec in allRecommendations) {
if (!seen.contains(rec.item.streamId)) {
scored.add(rec);
seen.add(rec.item.streamId);
}
}
// Sort by score
scored.sort((a, b) => b.score.compareTo(a.score));
return scored;
},
);
@@ -0,0 +1,481 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/models/playlist_config.dart';
import '../models/playlist.dart';
import '../services/xtream_service.dart';
/// EPG Program information
class EpgProgram {
final String id;
final String channelId;
final String title;
final String description;
final DateTime startTime;
final DateTime endTime;
final String? imageUrl;
final bool isNow;
final bool isNext;
EpgProgram({
required this.id,
required this.channelId,
required this.title,
required this.description,
required this.startTime,
required this.endTime,
this.imageUrl,
this.isNow = false,
this.isNext = false,
});
Duration get duration => endTime.difference(startTime);
double get progress {
if (!isNow) return 0;
final now = DateTime.now();
if (now.isBefore(startTime)) return 0;
if (now.isAfter(endTime)) return 100;
return ((now.difference(startTime).inSeconds) / duration.inSeconds) * 100;
}
}
/// EPG Grid View Screen (7 days, 24 hours)
class EpgGridScreen extends ConsumerStatefulWidget {
final Playlist playlist;
const EpgGridScreen({
Key? key,
required this.playlist,
}) : super(key: key);
@override
ConsumerState<EpgGridScreen> createState() => _EpgGridScreenState();
}
class _EpgGridScreenState extends ConsumerState<EpgGridScreen>
with TickerProviderStateMixin {
late TabController _tabController;
final _horizontalScroll = ScrollController();
final _verticalScroll = ScrollController();
Map<String, List<EpgProgram>> _epgData = {};
DateTime _selectedDate = DateTime.now();
bool _isLoading = false;
@override
void initState() {
super.initState();
_tabController = TabController(length: 7, vsync: this);
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadEpgData();
});
}
@override
void dispose() {
_tabController.dispose();
_horizontalScroll.dispose();
_verticalScroll.dispose();
super.dispose();
}
Future<void> _loadEpgData() async {
if (_isLoading) return;
setState(() => _isLoading = true);
try {
final service = ref.read(xtreamServiceProvider(widget.playlist));
final channels = await service.getLiveChannels();
final epgMap = <String, List<EpgProgram>>{};
// Load EPG for each channel
for (final channel in channels) {
try {
final epg = await service.getFullEpg(channel.streamId.toString());
final programs = _parseEpgPrograms(epg, channel.streamId.toString());
epgMap[channel.streamId.toString()] = programs;
} catch (e) {
print('Error loading EPG for ${channel.name}: $e');
epgMap[channel.streamId.toString()] = [];
}
}
setState(() {
_epgData = epgMap;
_isLoading = false;
});
} catch (e) {
print('Error loading EPG: $e');
setState(() => _isLoading = false);
}
}
List<EpgProgram> _parseEpgPrograms(
Map<String, dynamic> epgData, String channelId) {
final programs = <EpgProgram>[];
final now = DateTime.now();
// Parse EPG data structure
if (epgData.containsKey('epg_listings')) {
final listings = epgData['epg_listings'] as List;
for (final item in listings) {
try {
final startStr = item['start'] as String?;
final endStr = item['end'] as String?;
final title = item['title'] as String?;
final desc = item['description'] as String? ?? '';
if (startStr != null && endStr != null && title != null) {
final start = _parseEpgTime(startStr);
final end = _parseEpgTime(endStr);
programs.add(EpgProgram(
id: '${channelId}_${start.millisecondsSinceEpoch}',
channelId: channelId,
title: title,
description: desc,
startTime: start,
endTime: end,
isNow: now.isAfter(start) && now.isBefore(end),
isNext: start.isAfter(now) &&
start.difference(now).inMinutes < 60,
));
}
} catch (e) {
continue;
}
}
}
// Sort by start time
programs.sort((a, b) => a.startTime.compareTo(b.startTime));
return programs;
}
DateTime _parseEpgTime(String timeStr) {
try {
// Handle various formats: "12:30", "12:30:00", unix timestamp
if (timeStr.contains(':')) {
final parts = timeStr.split(':');
final hours = int.parse(parts[0]);
final minutes = int.parse(parts[1]);
final today = DateTime.now();
return DateTime(today.year, today.month, today.day, hours, minutes);
} else {
return DateTime.fromMillisecondsSinceEpoch(int.parse(timeStr) * 1000);
}
} catch (e) {
return DateTime.now();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('EPG Guide'),
bottom: TabBar(
controller: _tabController,
isScrollable: true,
onTap: (index) {
setState(() {
_selectedDate = DateTime.now().add(Duration(days: index));
});
},
tabs: List.generate(7, (index) {
final date = DateTime.now().add(Duration(days: index));
final day = DateFormat('EEE').format(date);
final dateNum = DateFormat('d').format(date);
return Tab(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(day, style: const TextStyle(fontSize: 11)),
Text(dateNum, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold)),
],
),
);
}),
),
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _buildEpgGrid(),
);
}
Widget _buildEpgGrid() {
if (_epgData.isEmpty) {
return const Center(
child: Text('No EPG data available'),
);
}
final channels = _epgData.keys.toList();
return Scrollbar(
controller: _horizontalScroll,
child: SingleChildScrollView(
controller: _horizontalScroll,
scrollDirection: Axis.horizontal,
child: Column(
children: [
// Time headers
SizedBox(
height: 60,
child: Row(
children: [
SizedBox(
width: 150,
child: Container(
decoration: BoxDecoration(
border: Border(
right: BorderSide(color: Colors.grey[700]!),
bottom: BorderSide(color: Colors.grey[700]!),
),
),
),
),
...List.generate(24, (hour) {
return Container(
width: 100,
height: 60,
decoration: BoxDecoration(
border: Border(
right: BorderSide(color: Colors.grey[700]!),
bottom: BorderSide(color: Colors.grey[700]!),
),
),
child: Center(
child: Text(
'$hour:00',
style: const TextStyle(fontSize: 11, fontWeight: FontWeight.bold),
),
),
);
}),
],
),
),
// Channel rows
Expanded(
child: Scrollbar(
controller: _verticalScroll,
child: ListView.builder(
controller: _verticalScroll,
itemCount: channels.length,
itemBuilder: (context, index) {
final channelId = channels[index];
final programs = _epgData[channelId] ?? [];
return _EpgChannelRow(
channelId: channelId,
programs: programs,
onProgramTap: (program) {
_showProgramDetail(program);
},
);
},
),
),
),
],
),
),
);
}
void _showProgramDetail(EpgProgram program) {
showModalBottomSheet(
context: context,
builder: (context) => _ProgramDetailSheet(program: program),
);
}
}
/// Individual channel row in EPG grid
class _EpgChannelRow extends StatelessWidget {
final String channelId;
final List<EpgProgram> programs;
final Function(EpgProgram) onProgramTap;
const _EpgChannelRow({
required this.channelId,
required this.programs,
required this.onProgramTap,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
// Channel name
Container(
width: 150,
height: 100,
decoration: BoxDecoration(
border: Border(
right: BorderSide(color: Colors.grey[700]!),
bottom: BorderSide(color: Colors.grey[700]!),
),
),
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(
channelId,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
),
),
),
// Programs
...programs.map((program) {
final duration = program.duration.inMinutes;
final width = (duration / 60 * 100).clamp(40, double.infinity).toDouble();
return GestureDetector(
onTap: () => onProgramTap(program),
child: Container(
width: width,
height: 100,
decoration: BoxDecoration(
color: program.isNow
? Colors.blue.withOpacity(0.7)
: program.isNext
? Colors.purple.withOpacity(0.5)
: Colors.grey[800],
border: Border(
right: BorderSide(color: Colors.grey[700]!),
bottom: BorderSide(color: Colors.grey[700]!),
),
),
child: Stack(
fit: StackFit.expand,
children: [
// Program info
Padding(
padding: const EdgeInsets.all(4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
program.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 2),
Text(
'${DateFormat('HH:mm').format(program.startTime)} - ${DateFormat('HH:mm').format(program.endTime)}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 8),
),
],
),
),
// Progress bar for now playing
if (program.isNow)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(4),
bottomRight: Radius.circular(4),
),
child: LinearProgressIndicator(
value: program.progress / 100,
minHeight: 3,
backgroundColor: Colors.white24,
valueColor:
const AlwaysStoppedAnimation(Colors.red),
),
),
),
],
),
),
);
}),
],
);
}
}
/// Program detail bottom sheet
class _ProgramDetailSheet extends StatelessWidget {
final EpgProgram program;
const _ProgramDetailSheet({required this.program});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
program.title,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Row(
children: [
Icon(
program.isNow ? Icons.play_circle : Icons.schedule,
color: program.isNow ? Colors.green : Colors.orange,
size: 16,
),
const SizedBox(width: 8),
Text(
'${DateFormat('HH:mm').format(program.startTime)} - ${DateFormat('HH:mm').format(program.endTime)}',
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
const SizedBox(width: 16),
Text(
'${program.duration.inMinutes} min',
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
],
),
const SizedBox(height: 16),
Text(
program.description.isEmpty ? 'No description available' : program.description,
style: const TextStyle(fontSize: 14),
),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton.icon(
onPressed: () => Navigator.pop(context),
icon: const Icon(Icons.play_arrow),
label: const Text('Watch Now'),
),
ElevatedButton.icon(
onPressed: () => Navigator.pop(context),
icon: const Icon(Icons.event),
label: const Text('Add Reminder'),
),
],
),
],
),
);
}
}
@@ -0,0 +1,308 @@
import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
/// Represents a download task
class DownloadTask {
final String id;
final String title;
final String url;
final String filePath;
final DownloadStatus status;
final double progress;
final int? totalSize;
final int downloadedSize;
DownloadTask({
required this.id,
required this.title,
required this.url,
required this.filePath,
this.status = DownloadStatus.pending,
this.progress = 0.0,
this.totalSize,
this.downloadedSize = 0,
});
DownloadTask copyWith({
DownloadStatus? status,
double? progress,
int? downloadedSize,
}) =>
DownloadTask(
id: id,
title: title,
url: url,
filePath: filePath,
status: status ?? this.status,
progress: progress ?? this.progress,
totalSize: totalSize,
downloadedSize: downloadedSize ?? this.downloadedSize,
);
}
enum DownloadStatus {
pending,
downloading,
paused,
completed,
failed,
cancelled,
}
/// Service for managing downloads
class DownloadService {
static const _downloadDir = './downloads';
static const _maxConcurrentDownloads = 3;
static const _maxStorageGb = 50;
final List<DownloadTask> _downloads = [];
final List<String> _activeDownloads = [];
/// Initialize download directory
static Future<void> initialize() async {
final dir = Directory(_downloadDir);
if (!dir.existsSync()) {
await dir.create(recursive: true);
}
}
/// Start a new download
Future<DownloadTask> startDownload({
required String id,
required String title,
required String url,
}) async {
final filePath = '$_downloadDir/$id.mp4';
final task = DownloadTask(
id: id,
title: title,
url: url,
filePath: filePath,
);
_downloads.add(task);
_processDownloadQueue();
return task;
}
/// Pause download
void pauseDownload(String id) {
final index = _downloads.indexWhere((t) => t.id == id);
if (index != -1) {
_downloads[index] = _downloads[index].copyWith(
status: DownloadStatus.paused,
);
}
}
/// Resume download
void resumeDownload(String id) {
final index = _downloads.indexWhere((t) => t.id == id);
if (index != -1) {
_downloads[index] = _downloads[index].copyWith(
status: DownloadStatus.pending,
);
_processDownloadQueue();
}
}
/// Cancel download
void cancelDownload(String id) {
final index = _downloads.indexWhere((t) => t.id == id);
if (index != -1) {
_downloads.removeAt(index);
_activeDownloads.remove(id);
}
}
/// Get all downloads
List<DownloadTask> getAllDownloads() => List.from(_downloads);
/// Get download progress
double getDownloadProgress(String id) {
final task = _downloads.firstWhere((t) => t.id == id, orElse: () => DownloadTask(
id: id,
title: '',
url: '',
filePath: '',
));
return task.progress;
}
/// Get available storage
Future<int> getAvailableStorage() async {
final dir = Directory(_downloadDir);
if (!dir.existsSync()) return _maxStorageGb * 1024 * 1024 * 1024;
int totalSize = 0;
final files = dir.listSync(recursive: true);
for (final file in files) {
if (file is File) {
totalSize += file.lengthSync();
}
}
return (_maxStorageGb * 1024 * 1024 * 1024) - totalSize;
}
/// Clean up old downloads based on space
Future<void> cleanupOldDownloads() async {
final available = await getAvailableStorage();
if (available < 1024 * 1024 * 1024) {
// Less than 1GB free
final dir = Directory(_downloadDir);
final files = dir.listSync()
.whereType<File>()
.toList();
// Sort by modification time, delete oldest first
files.sort((a, b) =>
a.statSync().modified.compareTo(b.statSync().modified));
for (final file in files.take(files.length ~/ 3)) {
try {
file.deleteSync();
} catch (e) {
print('Error deleting file: $e');
}
}
}
}
/// Process download queue
Future<void> _processDownloadQueue() async {
while (_activeDownloads.length < _maxConcurrentDownloads) {
final pendingIndex =
_downloads.indexWhere((t) => t.status == DownloadStatus.pending);
if (pendingIndex == -1) break;
final task = _downloads[pendingIndex];
_activeDownloads.add(task.id);
_downloads[pendingIndex] =
task.copyWith(status: DownloadStatus.downloading);
try {
await _downloadFile(task);
} catch (e) {
print('Download error: $e');
final index = _downloads.indexWhere((t) => t.id == task.id);
if (index != -1) {
_downloads[index] =
_downloads[index].copyWith(status: DownloadStatus.failed);
}
} finally {
_activeDownloads.remove(task.id);
}
}
}
/// Download file with progress tracking
Future<void> _downloadFile(DownloadTask task) async {
// Simplified version - in production use dio or http with progress tracking
final file = File(task.filePath);
if (!file.existsSync()) {
file.createSync(recursive: true);
}
// Stream download and update progress
// This is a placeholder - implement with actual download logic
for (int i = 0; i <= 100; i++) {
final index = _downloads.indexWhere((t) => t.id == task.id);
if (index != -1) {
_downloads[index] = _downloads[index].copyWith(
progress: i.toDouble(),
);
}
// Check if paused or cancelled
final currentTask = _downloads.firstWhere((t) => t.id == task.id, orElse: () => task);
if (currentTask.status == DownloadStatus.paused ||
!_activeDownloads.contains(task.id)) {
break;
}
await Future.delayed(const Duration(milliseconds: 100));
}
// Mark as completed
final index = _downloads.indexWhere((t) => t.id == task.id);
if (index != -1) {
_downloads[index] = _downloads[index].copyWith(
status: DownloadStatus.completed,
progress: 100.0,
);
}
}
/// Check if file is available for offline playback
bool isAvailableOffline(String id) {
final task = _downloads.firstWhere(
(t) => t.id == id,
orElse: () => DownloadTask(
id: id,
title: '',
url: '',
filePath: '',
),
);
if (task.status == DownloadStatus.completed) {
return File(task.filePath).existsSync();
}
return false;
}
/// Get file path for offline content
String? getOfflineFilePath(String id) {
final task = _downloads.firstWhere(
(t) => t.id == id && t.status == DownloadStatus.completed,
orElse: () => DownloadTask(
id: id,
title: '',
url: '',
filePath: '',
),
);
if (File(task.filePath).existsSync()) {
return task.filePath;
}
return null;
}
}
// Riverpod providers
final downloadServiceProvider = Provider<DownloadService>((ref) {
return DownloadService();
});
final downloadsProvider =
StateNotifierProvider<DownloadsNotifier, List<DownloadTask>>((ref) {
return DownloadsNotifier();
});
class DownloadsNotifier extends StateNotifier<List<DownloadTask>> {
DownloadsNotifier() : super([]);
void addDownload(DownloadTask task) {
state = [...state, task];
}
void updateDownload(DownloadTask task) {
state = [
for (final d in state)
if (d.id == task.id) task else d,
];
}
void removeDownload(String id) {
state = state.where((d) => d.id != id).toList();
}
void clearCompleted() {
state = state
.where((d) => d.status != DownloadStatus.completed)
.toList();
}
}
@@ -0,0 +1,176 @@
import 'package:http/http.dart' as http;
/// Subtitle track information
class SubtitleTrack {
final String id;
final String name;
final String language;
final String url;
final bool isEnabled;
SubtitleTrack({
required this.id,
required this.name,
required this.language,
required this.url,
this.isEnabled = false,
});
SubtitleTrack copyWith({bool? isEnabled}) => SubtitleTrack(
id: id,
name: name,
language: language,
url: url,
isEnabled: isEnabled ?? this.isEnabled,
);
}
/// Subtitle content with timing
class SubtitleEntry {
final int index;
final Duration startTime;
final Duration endTime;
final String text;
SubtitleEntry({
required this.index,
required this.startTime,
required this.endTime,
required this.text,
});
}
/// Service for handling subtitles
class SubtitleService {
static const _srtPattern = r'(\d+)\n(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})\n([\s\S]*?)(?=\n\n|\Z)';
/// Parse SRT subtitle content
static List<SubtitleEntry> parseSrt(String content) {
final entries = <SubtitleEntry>[];
final blocks = content.split('\n\n');
for (final block in blocks) {
if (block.trim().isEmpty) continue;
final lines = block.trim().split('\n');
if (lines.length < 3) continue;
try {
final index = int.parse(lines[0]);
final timeLine = lines[1];
final text = lines.sublist(2).join('\n').trim();
// Parse timing: 00:00:01,000 --> 00:00:05,000
final times = timeLine.split('-->');
if (times.length != 2) continue;
final startTime = _parseTime(times[0].trim());
final endTime = _parseTime(times[1].trim());
entries.add(SubtitleEntry(
index: index,
startTime: startTime,
endTime: endTime,
text: text,
));
} catch (e) {
continue;
}
}
return entries;
}
/// Parse WebVTT subtitle content
static List<SubtitleEntry> parseWebVtt(String content) {
final entries = <SubtitleEntry>[];
final blocks = content.split('\n\n');
for (final block in blocks) {
if (block.trim().isEmpty || block.startsWith('WEBVTT')) continue;
final lines = block.trim().split('\n');
if (lines.length < 2) continue;
try {
final timeLine = lines[0];
final text = lines.sublist(1).join('\n').trim();
// Parse timing: 00:00:01.000 --> 00:00:05.000
final times = timeLine.split('-->');
if (times.length != 2) continue;
final startTime = _parseWebVttTime(times[0].trim());
final endTime = _parseWebVttTime(times[1].trim());
entries.add(SubtitleEntry(
index: entries.length,
startTime: startTime,
endTime: endTime,
text: text,
));
} catch (e) {
continue;
}
}
return entries;
}
/// Get subtitle at specific time
static String? getSubtitleAtTime(List<SubtitleEntry> entries, Duration time) {
for (final entry in entries) {
if (time.compareTo(entry.startTime) >= 0 && time.compareTo(entry.endTime) <= 0) {
return entry.text;
}
}
return null;
}
/// Download subtitle from URL
static Future<String> downloadSubtitle(String url) async {
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return response.body;
}
throw Exception('Failed to download subtitle: ${response.statusCode}');
} catch (e) {
throw Exception('Error downloading subtitle: $e');
}
}
/// Parse time format HH:MM:SS,mmm (SRT)
static Duration _parseTime(String time) {
final parts = time.split(':');
final hours = int.parse(parts[0]);
final minutes = int.parse(parts[1]);
final secondsParts = parts[2].split(',');
final seconds = int.parse(secondsParts[0]);
final milliseconds = int.parse(secondsParts[1]);
return Duration(
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds,
);
}
/// Parse time format HH:MM:SS.mmm (WebVTT)
static Duration _parseWebVttTime(String time) {
final parts = time.split(':');
final hours = int.parse(parts[0]);
final minutes = int.parse(parts[1]);
final secondsParts = parts[2].split('.');
final seconds = int.parse(secondsParts[0]);
final milliseconds = int.parse(secondsParts[1].padEnd(3, '0'));
return Duration(
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds,
);
}
}
@@ -0,0 +1,535 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../providers/recommendations_provider.dart';
import '../../../core/models/playlist_config.dart';
import '../models/playlist.dart';
/// Widget showing "Continue Watching" section
class ContinueWatchingWidget extends ConsumerStatefulWidget {
final Playlist playlist;
final List<Playlist> content;
final VoidCallback? onItemTap;
const ContinueWatchingWidget({
Key? key,
required this.playlist,
required this.content,
this.onItemTap,
}) : super(key: key);
@override
ConsumerState<ContinueWatchingWidget> createState() =>
_ContinueWatchingWidgetState();
}
class _ContinueWatchingWidgetState
extends ConsumerState<ContinueWatchingWidget> {
@override
Widget build(BuildContext context) {
final watchHistory = ref.watch(watchHistoryProvider);
final continueWatching =
RecommendationService.getContinueWatching(watchHistory, widget.content);
if (continueWatching.isEmpty) {
return const SizedBox.shrink();
}
return Container(
margin: const EdgeInsets.symmetric(vertical: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Continue Watching',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
TextButton(
onPressed: () {
// Navigate to full continue watching list
},
child: const Text('View All'),
),
],
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
const SizedBox(width: 16),
...continueWatching.take(5).map((rec) {
final item = rec.item;
final percentage = watchHistory[item.streamId.toString()]
is Map
? (watchHistory[item.streamId.toString()]
as Map)['percentage'] as double? ??
0.0
: 0.0;
return Container(
margin: const EdgeInsets.only(right: 12),
child: _ContinueWatchingCard(
item: item,
progress: percentage,
onTap: widget.onItemTap,
),
);
}),
const SizedBox(width: 8),
],
),
),
],
),
);
}
}
class _ContinueWatchingCard extends StatelessWidget {
final Playlist item;
final double progress;
final VoidCallback? onTap;
const _ContinueWatchingCard({
required this.item,
required this.progress,
this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Poster with progress bar
Container(
width: 160,
height: 240,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.grey[800],
),
child: Stack(
fit: StackFit.expand,
children: [
// Poster image
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: CachedNetworkImage(
imageUrl: item.cover ?? '',
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Colors.grey[800],
),
errorWidget: (context, url, error) =>
Icon(Icons.image_not_supported,
color: Colors.grey[600]),
),
),
// Dark overlay at bottom
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withOpacity(0.8),
],
),
),
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Progress bar
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: progress / 100.0,
minHeight: 3,
backgroundColor: Colors.white30,
valueColor: AlwaysStoppedAnimation<Color>(
_getProgressColor(progress),
),
),
),
const SizedBox(height: 4),
Text(
'${progress.toStringAsFixed(0)}% watched',
style: const TextStyle(
color: Colors.white,
fontSize: 11,
),
),
],
),
),
),
// Play button overlay on hover
Positioned(
top: 0,
right: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.7),
shape: BoxShape.circle,
),
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
child: const Icon(
Icons.play_arrow,
color: Colors.white,
size: 24,
),
),
),
],
),
),
const SizedBox(height: 8),
// Title
SizedBox(
width: 160,
child: Text(
item.name ?? 'Unknown',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
],
),
);
}
Color _getProgressColor(double progress) {
if (progress < 30) return Colors.red;
if (progress < 70) return Colors.orange;
return Colors.green;
}
}
/// Widget showing trending/popular content
class TrendingWidget extends ConsumerWidget {
final Playlist playlist;
final List<Playlist> content;
final VoidCallback? onItemTap;
const TrendingWidget({
Key? key,
required this.playlist,
required this.content,
this.onItemTap,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final trending = ref.watch(trendingProvider);
final trendingContent =
RecommendationService.getTrending(trending, content);
if (trendingContent.isEmpty) {
return const SizedBox.shrink();
}
return Container(
margin: const EdgeInsets.symmetric(vertical: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const Icon(Icons.local_fire_department,
color: Colors.red, size: 24),
const SizedBox(width: 8),
const Text(
'Trending Now',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
TextButton(
onPressed: () {},
child: const Text('View All'),
),
],
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
const SizedBox(width: 16),
...trendingContent.take(5).map((rec) {
final item = rec.item;
final rank = trendingContent.indexOf(rec) + 1;
return Container(
margin: const EdgeInsets.only(right: 12),
child: _TrendingCard(
item: item,
rank: rank,
onTap: onItemTap,
),
);
}),
const SizedBox(width: 8),
],
),
),
],
),
);
}
}
class _TrendingCard extends StatelessWidget {
final Playlist item;
final int rank;
final VoidCallback? onTap;
const _TrendingCard({
required this.item,
required this.rank,
this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Stack(
children: [
// Card
Container(
width: 180,
height: 260,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.grey[800],
),
child: Column(
children: [
// Image
Expanded(
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
child: CachedNetworkImage(
imageUrl: item.cover ?? '',
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Colors.grey[800],
),
errorWidget: (context, url, error) =>
Icon(Icons.image_not_supported,
color: Colors.grey[600]),
),
),
),
// Info
Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name ?? 'Unknown',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
if (item.rating != null)
Row(
children: [
const Icon(Icons.star,
color: Colors.amber, size: 12),
const SizedBox(width: 4),
Text(
item.rating ?? '0',
style: const TextStyle(fontSize: 11),
),
],
),
],
),
),
],
),
),
// Rank badge
Positioned(
top: 8,
left: 8,
child: Container(
decoration: BoxDecoration(
color: _getRankColor(rank),
shape: BoxShape.circle,
),
width: 40,
height: 40,
child: Center(
child: Text(
'#$rank',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
),
),
],
),
);
}
Color _getRankColor(int rank) {
switch (rank) {
case 1:
return Colors.amber.shade700;
case 2:
return Colors.grey.shade600;
case 3:
return Colors.orange.shade700;
default:
return Colors.blue.shade700;
}
}
}
/// Widget showing recently added content
class RecentlyAddedWidget extends ConsumerWidget {
final Playlist playlist;
final List<Playlist> content;
final VoidCallback? onItemTap;
const RecentlyAddedWidget({
Key? key,
required this.playlist,
required this.content,
this.onItemTap,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final recent = RecommendationService.getRecentlyAdded(content);
if (recent.isEmpty) {
return const SizedBox.shrink();
}
return Container(
margin: const EdgeInsets.symmetric(vertical: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: const Text(
'Recently Added',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
const SizedBox(width: 16),
...recent.take(5).map((rec) {
return Container(
margin: const EdgeInsets.only(right: 12),
child: _RecentCard(
item: rec.item,
onTap: onItemTap,
),
);
}),
const SizedBox(width: 8),
],
),
),
],
),
);
}
}
class _RecentCard extends StatelessWidget {
final Playlist item;
final VoidCallback? onTap;
const _RecentCard({
required this.item,
this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
width: 140,
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.grey[800],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: CachedNetworkImage(
imageUrl: item.cover ?? '',
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Colors.grey[800],
),
errorWidget: (context, url, error) =>
Icon(Icons.image_not_supported, color: Colors.grey[600]),
),
),
),
);
}
}
@@ -0,0 +1,250 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/services/adaptive_bitrate_service.dart';
/// Widget for displaying and selecting video quality during playback
class QualitySelectorWidget extends ConsumerStatefulWidget {
final QualitySelector qualitySelector;
final VoidCallback onClose;
const QualitySelectorWidget({
Key? key,
required this.qualitySelector,
required this.onClose,
}) : super(key: key);
@override
ConsumerState<QualitySelectorWidget> createState() =>
_QualitySelectorWidgetState();
}
class _QualitySelectorWidgetState extends ConsumerState<QualitySelectorWidget> {
late List<QualityLevel> _availableQualities;
late QualityLevel _selectedQuality;
@override
void initState() {
super.initState();
_availableQualities = QualityProfiles.getBalancedProfiles();
_selectedQuality = widget.qualitySelector.currentQuality;
}
@override
Widget build(BuildContext context) {
final currentQuality = widget.qualitySelector.currentQuality;
final bandwidthMbps = widget.qualitySelector.getEstimatedBandwidthMbps();
return Dialog(
backgroundColor: Colors.black87,
insetPadding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Header
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.white24),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Video Quality',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: widget.onClose,
),
],
),
),
// Network Info
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white10,
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Current Bandwidth:',
style: TextStyle(color: Colors.white70, fontSize: 14),
),
Text(
'${bandwidthMbps.toStringAsFixed(1)} Mbps',
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
// Quality Options
ListView.builder(
shrinkWrap: true,
itemCount: _availableQualities.length,
itemBuilder: (context, index) {
final quality = _availableQualities[index];
final isSelected = quality == currentQuality;
return ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
leading: isSelected
? const Icon(Icons.check_circle, color: Colors.blue)
: const Icon(Icons.radio_button_unchecked,
color: Colors.white30),
title: Text(
quality.label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
),
),
subtitle: Text(
'${quality.bitrateBps ~/ 1000000} Mbps',
style: const TextStyle(color: Colors.white70, fontSize: 12),
),
onTap: () {
widget.qualitySelector.setQuality(quality);
setState(() {
_selectedQuality = quality;
});
},
);
},
),
// Auto Quality Option
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: Colors.white24),
),
),
child: ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
leading: const Icon(Icons.auto_awesome, color: Colors.amber),
title: const Text(
'Auto Quality',
style: TextStyle(
color: Colors.amber,
fontWeight: FontWeight.bold,
),
),
subtitle: const Text(
'Adjusts based on network speed',
style: TextStyle(color: Colors.white70, fontSize: 12),
),
onTap: () {
// Auto mode would be handled by the player
widget.onClose();
},
),
),
),
const SizedBox(height: 8),
],
),
);
}
}
/// Floating quality indicator (minimal UI during playback)
class QualityIndicator extends ConsumerWidget {
final QualitySelector qualitySelector;
final VoidCallback onTap;
const QualityIndicator({
Key? key,
required this.qualitySelector,
required this.onTap,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final quality = qualitySelector.currentQuality;
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.high_quality, color: Colors.white, size: 16),
const SizedBox(width: 4),
Text(
quality.resolution.split('x')[1], // Show just the height
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}
/// Bandwidth monitor widget (for debugging/info)
class BandwidthMonitor extends ConsumerWidget {
final QualitySelector qualitySelector;
const BandwidthMonitor({
Key? key,
required this.qualitySelector,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.speed, color: Colors.green, size: 14),
const SizedBox(width: 4),
Text(
'${qualitySelector.getEstimatedBandwidthMbps().toStringAsFixed(1)} Mbps',
style: const TextStyle(
color: Colors.white,
fontSize: 11,
),
),
],
),
);
}
}