mirror of
https://github.com/R0m1k3/xtremflow.git
synced 2026-10-18 04:39:41 +02:00
chore: Update dependencies, switch Flutter web renderer to HTML, replace media_kit with video_player/chewie, and remove Hive volume from Docker setup.
This commit is contained in:
1 parent
3c0d472a31
commit
0ca2835cba
16 files changed
+1282
-688
No files matched your search
@@ -40,14 +40,18 @@ class AuthNotifier extends StateNotifier<AuthState> {
|
||||
|
||||
try {
|
||||
final usersBox = HiveService.usersBox;
|
||||
final passwordHash = HiveService.hashPassword(password);
|
||||
|
||||
// Search for user with matching credentials
|
||||
// Search for user by username
|
||||
final user = usersBox.values.firstWhere(
|
||||
(user) => user.username == username && user.passwordHash == passwordHash,
|
||||
orElse: () => throw Exception('Invalid credentials'),
|
||||
(user) => user.username == username,
|
||||
orElse: () => throw Exception('User not found'),
|
||||
);
|
||||
|
||||
// Verify password using salt-based hashing
|
||||
if (!HiveService.verifyPassword(password, user.passwordHash)) {
|
||||
throw Exception('Invalid password');
|
||||
}
|
||||
|
||||
state = AuthState(currentUser: user, isLoading: false);
|
||||
return true;
|
||||
} catch (e) {
|
||||
@@ -59,6 +63,7 @@ class AuthNotifier extends StateNotifier<AuthState> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Logout current user
|
||||
void logout() {
|
||||
state = const AuthState();
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/models/playlist_config.dart';
|
||||
import '../services/xtream_service.dart';
|
||||
|
||||
/// Singleton Xtream service provider
|
||||
final xtreamServiceProvider = Provider<XtreamService>((ref) {
|
||||
final service = XtreamService();
|
||||
ref.onDispose(() => service.dispose());
|
||||
return service;
|
||||
});
|
||||
|
||||
/// Current selected playlist provider
|
||||
final selectedPlaylistProvider = StateProvider<PlaylistConfig?>((ref) => null);
|
||||
|
||||
/// Provider that watches for playlist changes and updates Xtream service
|
||||
final activeXtreamServiceProvider = Provider<XtreamService>((ref) {
|
||||
final service = ref.watch(xtreamServiceProvider);
|
||||
final playlist = ref.watch(selectedPlaylistProvider);
|
||||
|
||||
if (playlist != null) {
|
||||
service.setPlaylist(playlist);
|
||||
}
|
||||
|
||||
return service;
|
||||
});
|
||||
|
||||
/// Provider for live TV channels grouped by category
|
||||
final liveChannelsProvider = FutureProvider.autoDispose((ref) async {
|
||||
final service = ref.watch(activeXtreamServiceProvider);
|
||||
return await service.getLiveChannels();
|
||||
});
|
||||
|
||||
/// Provider for VOD items (movies) grouped by category
|
||||
final vodItemsProvider = FutureProvider.autoDispose((ref) async {
|
||||
final service = ref.watch(activeXtreamServiceProvider);
|
||||
return await service.getVodItems();
|
||||
});
|
||||
|
||||
/// Provider for series grouped by category
|
||||
final seriesProvider = FutureProvider.autoDispose((ref) async {
|
||||
final service = ref.watch(activeXtreamServiceProvider);
|
||||
return await service.getSeries();
|
||||
});
|
||||
|
||||
/// Provider for EPG of a specific stream
|
||||
final epgProvider = FutureProvider.family.autoDispose((ref, String streamId) async {
|
||||
final service = ref.watch(activeXtreamServiceProvider);
|
||||
return await service.getShortEpg(streamId);
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
import 'package:chewie/chewie.dart';
|
||||
import '../providers/xtream_provider.dart';
|
||||
import '../widgets/epg_overlay.dart';
|
||||
import '../../../core/models/iptv_models.dart';
|
||||
|
||||
/// Stream type enum for player
|
||||
enum StreamType { live, vod, series }
|
||||
|
||||
/// Video player screen with EPG overlay for live streams
|
||||
class PlayerScreen extends ConsumerStatefulWidget {
|
||||
final String streamId;
|
||||
final String title;
|
||||
final StreamType streamType;
|
||||
final String containerExtension;
|
||||
|
||||
const PlayerScreen({
|
||||
super.key,
|
||||
required this.streamId,
|
||||
required this.title,
|
||||
this.streamType = StreamType.live,
|
||||
this.containerExtension = 'm3u8',
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<PlayerScreen> createState() => _PlayerScreenState();
|
||||
}
|
||||
|
||||
class _PlayerScreenState extends ConsumerState<PlayerScreen> {
|
||||
late VideoPlayerController _videoPlayerController;
|
||||
ChewieController? _chewieController;
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initializePlayer();
|
||||
}
|
||||
|
||||
Future<void> _initializePlayer() async {
|
||||
try {
|
||||
final xtreamService = ref.read(activeXtreamServiceProvider);
|
||||
|
||||
// Generate stream URL based on type
|
||||
late String streamUrl;
|
||||
switch (widget.streamType) {
|
||||
case StreamType.live:
|
||||
streamUrl = xtreamService.getLiveStreamUrl(widget.streamId);
|
||||
break;
|
||||
case StreamType.vod:
|
||||
streamUrl = xtreamService.getVodStreamUrl(
|
||||
widget.streamId,
|
||||
widget.containerExtension,
|
||||
);
|
||||
break;
|
||||
case StreamType.series:
|
||||
streamUrl = xtreamService.getSeriesStreamUrl(
|
||||
widget.streamId,
|
||||
widget.containerExtension,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
_videoPlayerController = VideoPlayerController.networkUrl(
|
||||
Uri.parse(streamUrl),
|
||||
);
|
||||
|
||||
await _videoPlayerController.initialize();
|
||||
|
||||
_chewieController = ChewieController(
|
||||
videoPlayerController: _videoPlayerController,
|
||||
autoPlay: true,
|
||||
looping: false,
|
||||
aspectRatio: 16 / 9,
|
||||
allowFullScreen: true,
|
||||
allowMuting: true,
|
||||
showControls: true,
|
||||
placeholder: Container(
|
||||
color: Colors.black,
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
),
|
||||
errorBuilder: (context, errorMessage) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline,
|
||||
size: 48,
|
||||
color: Colors.red,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Error: $errorMessage',
|
||||
style: const TextStyle(color: Colors.white),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_videoPlayerController.dispose();
|
||||
_chewieController?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(widget.title),
|
||||
backgroundColor: Colors.black,
|
||||
),
|
||||
backgroundColor: Colors.black,
|
||||
body: _isLoading
|
||||
? const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
)
|
||||
: _errorMessage != null
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline,
|
||||
size: 64,
|
||||
color: Colors.red,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Failed to load stream',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_errorMessage!,
|
||||
style: const TextStyle(color: Colors.white70),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: Stack(
|
||||
children: [
|
||||
Center(
|
||||
child: _chewieController != null
|
||||
? Chewie(controller: _chewieController!)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
// EPG overlay for live streams
|
||||
if (widget.streamType == StreamType.live)
|
||||
Positioned(
|
||||
bottom: 80,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: EpgOverlay(streamId: widget.streamId),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,201 +1,225 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
|
||||
import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart';
|
||||
import '../../../core/models/playlist_config.dart';
|
||||
import '../models/xtream_models.dart';
|
||||
import '../../../core/models/iptv_models.dart';
|
||||
|
||||
/// Xtream Codes API Service
|
||||
///
|
||||
/// Handles all communication with Xtream API servers
|
||||
class XtreamService {
|
||||
final PlaylistConfig config;
|
||||
late final Dio _dio;
|
||||
late final CacheOptions _cacheOptions;
|
||||
|
||||
PlaylistConfig? _currentPlaylist;
|
||||
|
||||
// Cache for reducing API calls
|
||||
final Map<String, dynamic> _cache = {};
|
||||
static const _cacheDuration = Duration(minutes: 10);
|
||||
final Map<String, DateTime> _cacheTimestamps = {};
|
||||
XtreamService() {
|
||||
_dio = Dio(BaseOptions(
|
||||
connectTimeout: const Duration(seconds: 15),
|
||||
receiveTimeout: const Duration(seconds: 15),
|
||||
));
|
||||
|
||||
XtreamService(this.config) {
|
||||
_dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: config.apiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
queryParameters: {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
},
|
||||
),
|
||||
// Setup caching for API responses
|
||||
_cacheOptions = CacheOptions(
|
||||
store: HiveCacheStore('./cache'),
|
||||
policy: CachePolicy.forceCache,
|
||||
maxStale: const Duration(hours: 1),
|
||||
priority: CachePriority.high,
|
||||
);
|
||||
|
||||
// Add caching interceptor
|
||||
_dio.interceptors.add(
|
||||
InterceptorsWrapper(
|
||||
onRequest: (options, handler) {
|
||||
// Check cache before making request
|
||||
final cacheKey = options.uri.toString();
|
||||
if (_cache.containsKey(cacheKey)) {
|
||||
final timestamp = _cacheTimestamps[cacheKey];
|
||||
if (timestamp != null &&
|
||||
DateTime.now().difference(timestamp) < _cacheDuration) {
|
||||
// Return cached response
|
||||
return handler.resolve(
|
||||
Response(
|
||||
requestOptions: options,
|
||||
data: _cache[cacheKey],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
handler.next(options);
|
||||
},
|
||||
onResponse: (response, handler) {
|
||||
// Cache successful responses
|
||||
final cacheKey = response.requestOptions.uri.toString();
|
||||
_cache[cacheKey] = response.data;
|
||||
_cacheTimestamps[cacheKey] = DateTime.now();
|
||||
handler.next(response);
|
||||
},
|
||||
),
|
||||
);
|
||||
_dio.interceptors.add(DioCacheInterceptor(options: _cacheOptions));
|
||||
}
|
||||
|
||||
/// Initialize connection with a playlist
|
||||
void setPlaylist(PlaylistConfig playlist) {
|
||||
_currentPlaylist = playlist;
|
||||
}
|
||||
|
||||
/// Generate stream URL for live TV
|
||||
String getLiveStreamUrl(String streamId) {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
return '${_currentPlaylist!.dns}/live/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.m3u8';
|
||||
}
|
||||
|
||||
/// Generate stream URL for VOD (movies)
|
||||
String getVodStreamUrl(String streamId, String containerExtension) {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
return '${_currentPlaylist!.dns}/movie/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.$containerExtension';
|
||||
}
|
||||
|
||||
/// Generate stream URL for series episodes
|
||||
String getSeriesStreamUrl(String streamId, String containerExtension) {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
return '${_currentPlaylist!.dns}/series/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.$containerExtension';
|
||||
}
|
||||
|
||||
/// Authenticate and get server info
|
||||
Future<Map<String, dynamic>> authenticate() async {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
try {
|
||||
final response = await _dio.get('', queryParameters: {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
});
|
||||
final response = await _dio.get(
|
||||
_currentPlaylist!.apiBaseUrl,
|
||||
queryParameters: {
|
||||
'username': _currentPlaylist!.username,
|
||||
'password': _currentPlaylist!.password,
|
||||
},
|
||||
options: Options(extra: _cacheOptions.toExtra()),
|
||||
);
|
||||
|
||||
return response.data as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
throw Exception('Authentication failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get live streams with pagination
|
||||
Future<List<LiveChannel>> getLiveStreams({
|
||||
String? categoryId,
|
||||
int offset = 0,
|
||||
int limit = 100,
|
||||
}) async {
|
||||
/// Get all live TV channels grouped by category
|
||||
///
|
||||
/// Returns a Map where key is category name and value is list of channels
|
||||
Future<Map<String, List<Channel>>> getLiveChannels() async {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
try {
|
||||
final params = {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
'action': 'get_live_streams',
|
||||
if (categoryId != null) 'category_id': categoryId,
|
||||
};
|
||||
final response = await _dio.get(
|
||||
_currentPlaylist!.apiBaseUrl,
|
||||
queryParameters: {
|
||||
'username': _currentPlaylist!.username,
|
||||
'password': _currentPlaylist!.password,
|
||||
'action': 'get_live_streams',
|
||||
},
|
||||
options: Options(extra: _cacheOptions.toExtra()),
|
||||
);
|
||||
|
||||
final response = await _dio.get('', queryParameters: params);
|
||||
final data = response.data as List;
|
||||
final List<dynamic> streams = response.data as List<dynamic>;
|
||||
final Map<String, List<Channel>> groupedChannels = {};
|
||||
|
||||
// Apply manual pagination (Xtream doesn't support it natively)
|
||||
final paginatedData = data.skip(offset).take(limit).toList();
|
||||
for (final streamData in streams) {
|
||||
final channel = Channel.fromJson(streamData as Map<String, dynamic>);
|
||||
final categoryName = channel.categoryName.isEmpty ? 'Uncategorized' : channel.categoryName;
|
||||
|
||||
return paginatedData
|
||||
.map((json) => LiveChannel.fromJson(json as Map<String, dynamic>))
|
||||
if (!groupedChannels.containsKey(categoryName)) {
|
||||
groupedChannels[categoryName] = [];
|
||||
}
|
||||
groupedChannels[categoryName]!.add(channel);
|
||||
}
|
||||
|
||||
return groupedChannels;
|
||||
} catch (e) {
|
||||
throw Exception('Failed to fetch live channels: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all VOD items (movies) grouped by category
|
||||
Future<Map<String, List<VodItem>>> getVodItems() async {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
_currentPlaylist!.apiBaseUrl,
|
||||
queryParameters: {
|
||||
'username': _currentPlaylist!.username,
|
||||
'password': _currentPlaylist!.password,
|
||||
'action': 'get_vod_streams',
|
||||
},
|
||||
options: Options(extra: _cacheOptions.toExtra()),
|
||||
);
|
||||
|
||||
final List<dynamic> vods = response.data as List<dynamic>;
|
||||
final Map<String, List<VodItem>> groupedVods = {};
|
||||
|
||||
for (final vodData in vods) {
|
||||
final vod = VodItem.fromJson(vodData as Map<String, dynamic>);
|
||||
final categoryName = vod.categoryName.isEmpty ? 'Uncategorized' : vod.categoryName;
|
||||
|
||||
if (!groupedVods.containsKey(categoryName)) {
|
||||
groupedVods[categoryName] = [];
|
||||
}
|
||||
groupedVods[categoryName]!.add(vod);
|
||||
}
|
||||
|
||||
return groupedVods;
|
||||
} catch (e) {
|
||||
throw Exception('Failed to fetch VOD items: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all series grouped by category
|
||||
Future<Map<String, List<Series>>> getSeries() async {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
_currentPlaylist!.apiBaseUrl,
|
||||
queryParameters: {
|
||||
'username': _currentPlaylist!.username,
|
||||
'password': _currentPlaylist!.password,
|
||||
'action': 'get_series',
|
||||
},
|
||||
options: Options(extra: _cacheOptions.toExtra()),
|
||||
);
|
||||
|
||||
final List<dynamic> seriesList = response.data as List<dynamic>;
|
||||
final Map<String, List<Series>> groupedSeries = {};
|
||||
|
||||
for (final seriesData in seriesList) {
|
||||
final series = Series.fromJson(seriesData as Map<String, dynamic>);
|
||||
final categoryName = series.categoryName.isEmpty ? 'Uncategorized' : series.categoryName;
|
||||
|
||||
if (!groupedSeries.containsKey(categoryName)) {
|
||||
groupedSeries[categoryName] = [];
|
||||
}
|
||||
groupedSeries[categoryName]!.add(series);
|
||||
}
|
||||
|
||||
return groupedSeries;
|
||||
} catch (e) {
|
||||
throw Exception('Failed to fetch series: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get short EPG for a specific stream
|
||||
///
|
||||
/// Returns "Now" and "Next" program info
|
||||
Future<List<EpgEntry>> getShortEpg(String streamId) async {
|
||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
_currentPlaylist!.apiBaseUrl,
|
||||
queryParameters: {
|
||||
'username': _currentPlaylist!.username,
|
||||
'password': _currentPlaylist!.password,
|
||||
'action': 'get_short_epg',
|
||||
'stream_id': streamId,
|
||||
},
|
||||
options: Options(
|
||||
extra: CacheOptions(
|
||||
store: _cacheOptions.store,
|
||||
policy: CachePolicy.request,
|
||||
maxStale: const Duration(minutes: 5), // EPG changes frequently
|
||||
).toExtra(),
|
||||
),
|
||||
);
|
||||
|
||||
if (response.data == null || response.data['epg_listings'] == null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
final List<dynamic> epgData = response.data['epg_listings'] as List<dynamic>;
|
||||
return epgData
|
||||
.map((entry) => EpgEntry.fromJson(entry as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception('Failed to load live streams: $e');
|
||||
// EPG is optional, don't throw on failure
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Get VOD streams (movies) with pagination
|
||||
Future<List<Movie>> getMovies({
|
||||
String? categoryId,
|
||||
int offset = 0,
|
||||
int limit = 100,
|
||||
}) async {
|
||||
try {
|
||||
final params = {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
'action': 'get_vod_streams',
|
||||
if (categoryId != null) 'category_id': categoryId,
|
||||
};
|
||||
|
||||
final response = await _dio.get('', queryParameters: params);
|
||||
final data = response.data as List;
|
||||
|
||||
final paginatedData = data.skip(offset).take(limit).toList();
|
||||
|
||||
return paginatedData
|
||||
.map((json) => Movie.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception('Failed to load movies: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get series with pagination
|
||||
Future<List<Series>> getSeries({
|
||||
String? categoryId,
|
||||
int offset = 0,
|
||||
int limit = 100,
|
||||
}) async {
|
||||
try {
|
||||
final params = {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
'action': 'get_series',
|
||||
if (categoryId != null) 'category_id': categoryId,
|
||||
};
|
||||
|
||||
final response = await _dio.get('', queryParameters: params);
|
||||
final data = response.data as List;
|
||||
|
||||
final paginatedData = data.skip(offset).take(limit).toList();
|
||||
|
||||
return paginatedData
|
||||
.map((json) => Series.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception('Failed to load series: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get live categories
|
||||
Future<List<Category>> getLiveCategories() async {
|
||||
try {
|
||||
final response = await _dio.get('', queryParameters: {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
'action': 'get_live_categories',
|
||||
});
|
||||
|
||||
final data = response.data as List;
|
||||
return data
|
||||
.map((json) => Category.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception('Failed to load categories: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get short EPG for a specific channel
|
||||
Future<ShortEPG> getShortEPG(String channelId) async {
|
||||
try {
|
||||
final response = await _dio.get('', queryParameters: {
|
||||
'username': config.username,
|
||||
'password': config.password,
|
||||
'action': 'get_short_epg',
|
||||
'stream_id': channelId,
|
||||
'limit': '2', // Only get current and next
|
||||
});
|
||||
|
||||
return ShortEPG.fromJson(response.data as Map<String, dynamic>);
|
||||
} catch (e) {
|
||||
// EPG might not be available for all channels
|
||||
return const ShortEPG();
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear cache
|
||||
void clearCache() {
|
||||
_cache.clear();
|
||||
_cacheTimestamps.clear();
|
||||
/// Dispose resources
|
||||
void dispose() {
|
||||
_dio.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider for Xtream service (requires playlist config)
|
||||
final xtreamServiceProvider = Provider.family<XtreamService, PlaylistConfig>(
|
||||
(ref, config) => XtreamService(config),
|
||||
);
|
||||
@@ -0,0 +1,131 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../providers/xtream_provider.dart';
|
||||
|
||||
/// EPG overlay widget showing "Now" and "Next" programs
|
||||
class EpgOverlay extends ConsumerWidget {
|
||||
final String streamId;
|
||||
|
||||
const EpgOverlay({
|
||||
super.key,
|
||||
required this.streamId,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final epgAsync = ref.watch(epgProvider(streamId));
|
||||
|
||||
return epgAsync.when(
|
||||
data: (epgEntries) {
|
||||
if (epgEntries.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
// Get "Now" and "Next" programs
|
||||
final now = DateTime.now();
|
||||
final currentProgram = epgEntries.firstWhere(
|
||||
(entry) {
|
||||
final start = DateTime.parse(entry.start);
|
||||
final end = DateTime.parse(entry.end);
|
||||
return now.isAfter(start) && now.isBefore(end);
|
||||
},
|
||||
orElse: () => epgEntries.first,
|
||||
);
|
||||
|
||||
final progress = currentProgram.getProgress();
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.all(16),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withOpacity(0.7),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Current program
|
||||
Text(
|
||||
'NOW: ${currentProgram.title}',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Progress bar
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: progress,
|
||||
backgroundColor: Colors.white24,
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(Colors.red),
|
||||
minHeight: 4,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Time info
|
||||
Text(
|
||||
'${_formatTime(currentProgram.start)} - ${_formatTime(currentProgram.end)}',
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
// Description if available
|
||||
if (currentProgram.description.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
currentProgram.description,
|
||||
style: const TextStyle(
|
||||
color: Colors.white60,
|
||||
fontSize: 11,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
// Next program
|
||||
if (epgEntries.length > 1) ...[
|
||||
const SizedBox(height: 8),
|
||||
const Divider(color: Colors.white24, height: 1),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'NEXT: ${epgEntries[1].title}',
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 12,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Text(
|
||||
_formatTime(epgEntries[1].start),
|
||||
style: const TextStyle(
|
||||
color: Colors.white60,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
loading: () => const SizedBox.shrink(),
|
||||
error: (_, __) => const SizedBox.shrink(),
|
||||
);
|
||||
}
|
||||
|
||||
String _formatTime(String isoString) {
|
||||
try {
|
||||
final dateTime = DateTime.parse(isoString);
|
||||
return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
|
||||
} catch (e) {
|
||||
return isoString;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,197 +1,183 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import '../../../core/models/playlist_config.dart';
|
||||
import '../services/xtream_service.dart';
|
||||
import '../models/xtream_models.dart';
|
||||
import '../screens/video_player_screen.dart';
|
||||
import 'epg_widget.dart';
|
||||
import '../providers/xtream_provider.dart';
|
||||
import '../screens/player_screen.dart';
|
||||
import '../../../core/models/iptv_models.dart';
|
||||
|
||||
/// Live TV tab with group-based pagination
|
||||
class LiveTVTab extends ConsumerStatefulWidget {
|
||||
final PlaylistConfig playlist;
|
||||
|
||||
const LiveTVTab({super.key, required this.playlist});
|
||||
const LiveTVTab({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<LiveTVTab> createState() => _LiveTVTabState();
|
||||
}
|
||||
|
||||
class _LiveTVTabState extends ConsumerState<LiveTVTab> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final List<LiveChannel> _channels = [];
|
||||
bool _isLoading = false;
|
||||
bool _hasMore = true;
|
||||
int _currentOffset = 0;
|
||||
static const int _pageSize = 100;
|
||||
class _LiveTVTabState extends ConsumerState<LiveTVTab>
|
||||
with AutomaticKeepAliveClientMixin {
|
||||
final Map<String, int> _currentPages = {};
|
||||
final Map<String, bool> _expandedCategories = {};
|
||||
static const int _itemsPerPage = 100;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadMoreChannels();
|
||||
_scrollController.addListener(_onScroll);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onScroll() {
|
||||
if (_scrollController.position.pixels >=
|
||||
_scrollController.position.maxScrollExtent * 0.8) {
|
||||
_loadMoreChannels();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadMoreChannels() async {
|
||||
if (_isLoading || !_hasMore) return;
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final service = ref.read(xtreamServiceProvider(widget.playlist));
|
||||
final newChannels = await service.getLiveStreams(
|
||||
offset: _currentOffset,
|
||||
limit: _pageSize,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_channels.addAll(newChannels);
|
||||
_currentOffset += _pageSize;
|
||||
_hasMore = newChannels.length == _pageSize;
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Failed to load channels: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
bool get wantKeepAlive => true;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_channels.isEmpty && !_isLoading) {
|
||||
return const Center(child: Text('No channels available'));
|
||||
}
|
||||
super.build(context);
|
||||
|
||||
return GridView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.all(8),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 4,
|
||||
crossAxisSpacing: 8,
|
||||
mainAxisSpacing: 8,
|
||||
childAspectRatio: 0.75,
|
||||
),
|
||||
itemCount: _channels.length + (_hasMore ? 1 : 0),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= _channels.length) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
final channelsAsync = ref.watch(liveChannelsProvider);
|
||||
|
||||
return channelsAsync.when(
|
||||
data: (groupedChannels) {
|
||||
if (groupedChannels.isEmpty) {
|
||||
return const Center(
|
||||
child: Text('No live channels available'),
|
||||
);
|
||||
}
|
||||
|
||||
final channel = _channels[index];
|
||||
return _ChannelCard(
|
||||
channel: channel,
|
||||
playlist: widget.playlist,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
final categories = groupedChannels.keys.toList()..sort();
|
||||
|
||||
class _ChannelCard extends StatelessWidget {
|
||||
final LiveChannel channel;
|
||||
final PlaylistConfig playlist;
|
||||
return ListView.builder(
|
||||
itemCount: categories.length,
|
||||
itemBuilder: (context, index) {
|
||||
final category = categories[index];
|
||||
final channels = groupedChannels[category]!;
|
||||
final currentPage = _currentPages[category] ?? 0;
|
||||
final isExpanded = _expandedCategories[category] ?? false;
|
||||
|
||||
const _ChannelCard({
|
||||
required this.channel,
|
||||
required this.playlist,
|
||||
});
|
||||
// Calculate pagination
|
||||
final totalPages = (channels.length / _itemsPerPage).ceil();
|
||||
final startIndex = currentPage * _itemsPerPage;
|
||||
final endIndex = (startIndex + _itemsPerPage > channels.length)
|
||||
? channels.length
|
||||
: startIndex + _itemsPerPage;
|
||||
final paginatedChannels = channels.sublist(startIndex, endIndex);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: () {
|
||||
final streamUrl = channel.getStreamUrl(
|
||||
playlist.dns,
|
||||
playlist.username,
|
||||
playlist.password,
|
||||
);
|
||||
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
streamUrl: streamUrl,
|
||||
title: channel.name,
|
||||
posterUrl: channel.streamIcon,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: channel.streamIcon != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: channel.streamIcon!,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => Container(
|
||||
color: Colors.grey.shade800,
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
color: Colors.grey.shade800,
|
||||
child: const Icon(Icons.live_tv, size: 48),
|
||||
),
|
||||
)
|
||||
: Container(
|
||||
color: Colors.grey.shade800,
|
||||
child: const Icon(Icons.live_tv, size: 48),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: ExpansionPanelList(
|
||||
expansionCallback: (panelIndex, expanded) {
|
||||
setState(() {
|
||||
_expandedCategories[category] = !expanded;
|
||||
});
|
||||
},
|
||||
children: [
|
||||
Text(
|
||||
channel.name,
|
||||
style: GoogleFonts.roboto(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
ExpansionPanel(
|
||||
headerBuilder: (context, isExpanded) {
|
||||
return ListTile(
|
||||
title: Text(
|
||||
category,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
subtitle: Text('${channels.length} channels'),
|
||||
);
|
||||
},
|
||||
body: Column(
|
||||
children: [
|
||||
// Pagination controls
|
||||
if (totalPages > 1)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: currentPage > 0
|
||||
? () {
|
||||
setState(() {
|
||||
_currentPages[category] = currentPage - 1;
|
||||
});
|
||||
}
|
||||
: null,
|
||||
),
|
||||
Text(
|
||||
'Page ${currentPage + 1} of $totalPages',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_forward),
|
||||
onPressed: currentPage < totalPages - 1
|
||||
? () {
|
||||
setState(() {
|
||||
_currentPages[category] = currentPage + 1;
|
||||
});
|
||||
}
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Channel list
|
||||
ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: paginatedChannels.length,
|
||||
itemExtent: 72,
|
||||
itemBuilder: (context, channelIndex) {
|
||||
final channel = paginatedChannels[channelIndex];
|
||||
return _buildChannelTile(context, channel);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
isExpanded: isExpanded,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// EPG Display
|
||||
if (channel.epgChannelId != null)
|
||||
EPGWidget(
|
||||
channelId: channel.streamId,
|
||||
playlist: playlist,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, stack) => Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.error_outline, size: 48, color: Colors.red),
|
||||
const SizedBox(height: 16),
|
||||
Text('Error loading channels: $error'),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildChannelTile(BuildContext context, Channel channel) {
|
||||
return ListTile(
|
||||
leading: channel.streamIcon.isNotEmpty
|
||||
? CachedNetworkImage(
|
||||
imageUrl: channel.streamIcon,
|
||||
width: 48,
|
||||
height: 48,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => const Icon(Icons.tv),
|
||||
errorWidget: (context, url, error) => const Icon(Icons.broken_image),
|
||||
)
|
||||
: const Icon(Icons.tv),
|
||||
title: Text(
|
||||
channel.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: channel.num.isNotEmpty
|
||||
? Text('Ch. ${channel.num}')
|
||||
: null,
|
||||
trailing: const Icon(Icons.play_circle_outline),
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) => PlayerScreen(
|
||||
streamId: channel.streamId,
|
||||
title: channel.name,
|
||||
streamType: StreamType.live,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,3 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import '../../../core/models/playlist_config.dart';
|
||||
import '../services/xtream_service.dart';
|
||||
import '../models/xtream_models.dart';
|
||||
import '../screens/video_player_screen.dart';
|
||||
|
||||
class MoviesTab extends ConsumerStatefulWidget {
|
||||
final PlaylistConfig playlist;
|
||||
|
||||
const MoviesTab({super.key, required this.playlist});
|
||||
|
||||
Reference in new issue
Block a user