From 2406b9b100a97ef6594c69ada847a3b3f332dee2 Mon Sep 17 00:00:00 2001 From: Michael SCHAL Date: Wed, 10 Dec 2025 22:16:51 +0100 Subject: [PATCH] feat: introduce XtreamServiceMobile for IPTV API interactions and DnsFallbackInterceptor for network robustness. --- lib/core/services/settings_api_service.dart | 4 +- lib/core/theme/app_colors.dart | 11 + lib/features/iptv/models/xtream_models.dart | 10 +- .../iptv/screens/lite_player_screen.dart | 586 ++++++++++++++++++ .../mobile_playlist_selection_screen.dart | 167 +++-- .../screens/mobile_series_detail_screen.dart | 53 +- .../iptv/screens/native_player_screen.dart | 290 +++++++-- .../iptv/widgets/mobile_live_tv_tab.dart | 184 ++++-- .../iptv/widgets/mobile_movies_tab.dart | 318 ++++++---- .../iptv/widgets/mobile_series_tab.dart | 121 ++-- .../iptv/widgets/mobile_settings_tab.dart | 75 ++- .../providers/mobile_settings_providers.dart | 33 + .../providers/mobile_xtream_providers.dart | 17 + lib/mobile/widgets/mobile_scaffold.dart | 92 ++- lib/mobile/widgets/tv_focusable.dart | 130 ++++ pubspec.yaml | 1 + 16 files changed, 1693 insertions(+), 399 deletions(-) create mode 100644 lib/mobile/features/iptv/screens/lite_player_screen.dart create mode 100644 lib/mobile/widgets/tv_focusable.dart diff --git a/lib/core/services/settings_api_service.dart b/lib/core/services/settings_api_service.dart index 06d7a14..fc50cb7 100644 --- a/lib/core/services/settings_api_service.dart +++ b/lib/core/services/settings_api_service.dart @@ -9,7 +9,7 @@ class SettingsApiService { // Restore token from localStorage before making the request _api.restoreToken(); - if (_api.getStoredToken() == null) { + if (_api.getToken() == null) { print('[SettingsAPI] getSettings: No auth token found'); return null; } @@ -38,7 +38,7 @@ class SettingsApiService { // Restore token from localStorage before making the request _api.restoreToken(); - if (_api.getStoredToken() == null) { + if (_api.getToken() == null) { print('[SettingsAPI] saveSettings: No auth token found'); return false; } diff --git a/lib/core/theme/app_colors.dart b/lib/core/theme/app_colors.dart index a5c44ba..088d83e 100644 --- a/lib/core/theme/app_colors.dart +++ b/lib/core/theme/app_colors.dart @@ -36,6 +36,17 @@ class AppColors { end: Alignment.bottomRight, ); + /// Apple TV Style Background Gradient (Grey/Black Radial) + static const RadialGradient appleTvGradient = RadialGradient( + center: Alignment.center, + radius: 1.5, + colors: [ + Color(0xFF2C2C2E), // Apple Dark Gray + Color(0xFF000000), // Black + ], + stops: [0.0, 1.0], + ); + // ============ TEXT ============ static const Color textPrimary = Color(0xFFFFFFFF); static const Color textSecondary = Color(0xFF9E9E9E); // Medium Grey diff --git a/lib/features/iptv/models/xtream_models.dart b/lib/features/iptv/models/xtream_models.dart index 6f41e20..aa5b9ac 100644 --- a/lib/features/iptv/models/xtream_models.dart +++ b/lib/features/iptv/models/xtream_models.dart @@ -134,6 +134,7 @@ class Season { class Episode { final String id; final int episodeNum; + final int seasonNum; // Added field final String title; final String? containerExtension; final String? info; @@ -143,6 +144,7 @@ class Episode { const Episode({ required this.id, required this.episodeNum, + this.seasonNum = 0, // Default to 0 if unknown required this.title, this.containerExtension, this.info, @@ -150,10 +152,11 @@ class Episode { this.durationSecs, }); - factory Episode.fromJson(Map json) { + factory Episode.fromJson(Map json, {int? season}) { // Accept season param return Episode( id: json['id']?.toString() ?? '', episodeNum: int.tryParse(json['episode_num']?.toString() ?? '1') ?? 1, + seasonNum: season ?? int.tryParse(json['season']?.toString() ?? '0') ?? 0, title: json['title']?.toString() ?? 'Episode ${json['episode_num'] ?? 1}', containerExtension: json['container_extension']?.toString() ?? 'mkv', info: json['info']?.toString(), @@ -161,6 +164,9 @@ class Episode { durationSecs: int.tryParse(json['duration_secs']?.toString() ?? '0'), ); } + + // Getter for compatibility + String get streamId => id; String getStreamUrl(String dns, String username, String password) { return '$dns/series/$username/$password/$id.${containerExtension ?? 'mkv'}'; @@ -205,7 +211,7 @@ class SeriesInfo { episodesData.forEach((seasonNum, episodesList) { final seasonInt = int.tryParse(seasonNum) ?? 1; final episodeList = (episodesList as List?) - ?.map((e) => Episode.fromJson(e as Map)) + ?.map((e) => Episode.fromJson(e as Map, season: seasonInt)) .toList() ?? []; episodes[seasonInt] = episodeList; }); diff --git a/lib/mobile/features/iptv/screens/lite_player_screen.dart b/lib/mobile/features/iptv/screens/lite_player_screen.dart new file mode 100644 index 0000000..5195373 --- /dev/null +++ b/lib/mobile/features/iptv/screens/lite_player_screen.dart @@ -0,0 +1,586 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:video_player/video_player.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:xtremflow/mobile/widgets/tv_focusable.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:xtremflow/core/models/iptv_models.dart'; +import 'package:xtremflow/core/models/playlist_config.dart'; +import 'package:xtremflow/features/iptv/services/xtream_service_mobile.dart'; +import 'package:xtremflow/mobile/providers/mobile_settings_providers.dart'; +import 'package:xtremflow/core/theme/app_colors.dart'; +import 'package:xtremflow/mobile/providers/mobile_xtream_providers.dart'; +import 'package:xtremflow/mobile/features/iptv/screens/native_player_screen.dart' show StreamType; +import 'package:xtremflow/features/iptv/models/xtream_models.dart' as xm; + +/// Lite version of the player using standard video_player (ExoPlayer on Android) +/// Targeted for 1GB RAM devices where MPV is too heavy. +class LitePlayerScreen extends ConsumerStatefulWidget { + final String streamId; + final String title; + final StreamType streamType; + final String? containerExtension; + final PlaylistConfig playlist; + final List? channels; + final int initialIndex; + + // For series episodes + final dynamic seriesId; + final int? season; + final int? episodeNum; + + const LitePlayerScreen({ + super.key, + required this.streamId, + required this.title, + required this.playlist, + required this.streamType, + this.containerExtension, + this.channels, + this.initialIndex = 0, + this.seriesId, + this.season, + this.episodeNum, + }); + + @override + ConsumerState createState() => _LitePlayerScreenState(); +} + +class _LitePlayerScreenState extends ConsumerState with WidgetsBindingObserver { + VideoPlayerController? _controller; + XtreamServiceMobile? _xtreamService; + + bool _isLoading = true; + String? _errorMessage; + late int _currentIndex; + bool _showControls = true; + bool _isPlaying = false; + + // EPG + xm.ShortEPG? _epg; + Timer? _epgTimer; + + // Progress & Seeking + Duration _position = Duration.zero; + Duration _duration = Duration.zero; + bool _isSeeking = false; + + // Focus Nodes + final FocusNode _playPauseFocusNode = FocusNode(); + final FocusNode _backFocusNode = FocusNode(); + + Timer? _controlsTimer; + Timer? _clockTimer; + String _currentTime = ''; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + HardwareKeyboard.instance.addHandler(_handleKeyEvent); + + _currentIndex = widget.initialIndex; + _startClock(); + + // Lock orientation + SystemChrome.setPreferredOrientations([ + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); + + _initializeService(); + } + + Future _initializeService() async { + try { + final dir = await getApplicationDocumentsDirectory(); + _xtreamService = XtreamServiceMobile(dir.path); + await _xtreamService!.setPlaylistAsync(widget.playlist); + _loadStream(); + _updateEPG(); // Initial Load + + // Update EPG periodically for Live TV + if (widget.streamType == StreamType.live) { + _epgTimer = Timer.periodic(const Duration(minutes: 5), (_) => _updateEPG()); + } + } catch (e) { + if (mounted) setState(() => _errorMessage = "Service Error: $e"); + } + } + + Future _updateEPG() async { + if (widget.streamType != StreamType.live || _xtreamService == null) return; + + try { + final currentChannelId = widget.channels?[_currentIndex].streamId ?? widget.streamId; + // Get EPG for current channel + final epgData = await _xtreamService!.getShortEPG(currentChannelId); + if (mounted) { + setState(() => _epg = epgData); + } + } catch (_) {} + } + + Future _loadStream() async { + if (_xtreamService == null) return; + + // cleanup previous + await _controller?.dispose(); + _controller = null; + + if (!mounted) return; + setState(() { + _isLoading = true; + _errorMessage = null; + }); + + try { + final currentStreamId = widget.channels != null && widget.channels!.isNotEmpty + ? widget.channels![_currentIndex].streamId + : widget.streamId; + + // Update EPG when changing channels + if (widget.streamType == StreamType.live) { + _updateEPG(); + } + + String streamUrl; + if (widget.streamType == StreamType.live) { + streamUrl = _xtreamService!.getLiveStreamUrl(currentStreamId); + } else if (widget.streamType == StreamType.vod) { + streamUrl = _xtreamService!.getVodStreamUrl(currentStreamId, widget.containerExtension ?? 'mp4'); + } else { + streamUrl = _xtreamService!.getSeriesStreamUrl(currentStreamId, widget.containerExtension ?? 'mp4'); + } + + final controller = VideoPlayerController.networkUrl( + Uri.parse(streamUrl), + httpHeaders: {'User-Agent': 'XtremFlow/1.0'}, + ); + + _controller = controller; + await controller.initialize(); + + if (!mounted) { + await controller.dispose(); + return; + } + + await controller.play(); + setState(() { + _isLoading = false; + _isPlaying = true; + _duration = controller.value.duration; + }); + _resetControlsTimer(); + + // Listen for errors and completion via controller listener + controller.addListener(_videoListener); + + } catch (e) { + if (mounted) { + setState(() { + _isLoading = false; + _errorMessage = "Playback Error: $e"; + }); + } + } + } + + void _videoListener() { + if (_controller == null || !mounted) return; + + // Update Play/Pause state + final isPlaying = _controller!.value.isPlaying; + if (isPlaying != _isPlaying) { + setState(() => _isPlaying = isPlaying); + } + + // Update Duration/Position (if not seeking) + if (!_isSeeking) { + final pos = _controller!.value.position; + final dur = _controller!.value.duration; + if (pos != _position || dur != _duration) { + setState(() { + _position = pos; + _duration = dur; + }); + } + } + + if (_controller!.value.hasError) { + setState(() => _errorMessage = _controller!.value.errorDescription); + } + } + + void _onUserInteraction() { + setState(() => _showControls = true); + _resetControlsTimer(); + } + + void _resetControlsTimer() { + _controlsTimer?.cancel(); + if (_showControls && _isPlaying) { + _controlsTimer = Timer(const Duration(seconds: 5), () { + if (mounted) setState(() => _showControls = false); + }); + } + } + + void _togglePlayPause() { + if (_controller == null) return; + if (_controller!.value.isPlaying) { + _controller!.pause(); + } else { + _controller!.play(); + } + _onUserInteraction(); + } + + void _playNext() { + if (widget.channels == null || widget.channels!.isEmpty) return; + final nextIndex = (_currentIndex + 1) % widget.channels!.length; + _switchChannel(nextIndex); + } + + void _playPrevious() { + if (widget.channels == null || widget.channels!.isEmpty) return; + final prevIndex = (_currentIndex - 1 + widget.channels!.length) % widget.channels!.length; + _switchChannel(prevIndex); + } + + void _switchChannel(int index) { + setState(() => _currentIndex = index); + _loadStream(); + } + + Future _seek(Duration offset) async { + if (_controller == null || !_controller!.value.isInitialized) return; + final newPos = _controller!.value.position + offset; + final clamped = Duration( + milliseconds: newPos.inMilliseconds.clamp(0, _controller!.value.duration.inMilliseconds) + ); + await _controller!.seekTo(clamped); + _onUserInteraction(); + } + + // Simplified Key Handler + bool _handleKeyEvent(KeyEvent event) { + if (event is! KeyDownEvent) return false; + final key = event.logicalKey; + + // Media Keys (Remote) + if (key == LogicalKeyboardKey.mediaPlay || key == LogicalKeyboardKey.mediaPause || key == LogicalKeyboardKey.mediaPlayPause) { + _togglePlayPause(); + return true; + } + + if (key == LogicalKeyboardKey.select || key == LogicalKeyboardKey.enter || key == LogicalKeyboardKey.space) { + if (!_showControls) { + _onUserInteraction(); + return true; + } + // If controls visible, let focus system handle it + return false; + } + + // Seek / Channel Change + + if (key == LogicalKeyboardKey.arrowDown || key == LogicalKeyboardKey.channelDown) { + // User requested "Down" => Previous Channel (Index - 1) + if (widget.streamType == StreamType.live) { + _playPrevious(); + _onUserInteraction(); // Show OSD + } + return true; + } + + if (key == LogicalKeyboardKey.arrowUp || key == LogicalKeyboardKey.channelUp) { + // User requested "Up" => Next Channel (Index + 1) + if (widget.streamType == StreamType.live) { + _playNext(); + _onUserInteraction(); // Show OSD + } + return true; + } + if (widget.streamType != StreamType.live) { + if (key == LogicalKeyboardKey.arrowLeft) { + _seek(const Duration(seconds: -10)); + return true; + } + if (key == LogicalKeyboardKey.arrowRight) { + _seek(const Duration(seconds: 10)); + return true; + } + } + + if (key == LogicalKeyboardKey.escape || key == LogicalKeyboardKey.goBack) { + if (_showControls) { + setState(() => _showControls = false); + } else { + // Force pop completely to return to list, not just playlist selection + // Check navigator stack if needed, but standard pop should work if pushed correctly + Navigator.pop(context); + } + return true; + } + + return false; + } + + void _startClock() { + _updateTime(); + _clockTimer = Timer.periodic(const Duration(seconds: 1), (_) => _updateTime()); + } + + void _updateTime() { + if (mounted) { + final now = DateTime.now(); + setState(() { + _currentTime = "${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}"; + }); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + HardwareKeyboard.instance.removeHandler(_handleKeyEvent); + _controlsTimer?.cancel(); + _clockTimer?.cancel(); + _epgTimer?.cancel(); + _controller?.dispose(); + _xtreamService?.dispose(); + _playPauseFocusNode.dispose(); + _backFocusNode.dispose(); + + SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + super.dispose(); + } + + String _formatDuration(Duration duration) { + String twoDigits(int n) => n.toString().padLeft(2, '0'); + String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); + String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60)); + return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds"; + } + + @override + Widget build(BuildContext context) { + final title = widget.channels != null && widget.channels!.isNotEmpty + ? widget.channels![_currentIndex].name + : widget.title; + + return Scaffold( + backgroundColor: Colors.black, + body: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _onUserInteraction, + child: Stack( + children: [ + Center( + child: _controller != null && _controller!.value.isInitialized + ? AspectRatio( + aspectRatio: _controller!.value.aspectRatio, + child: VideoPlayer(_controller!), + ) + : const CircularProgressIndicator(color: AppColors.primary), + ), + + if (_errorMessage != null) + Center(child: Text(_errorMessage!, style: const TextStyle(color: Colors.red))), + + if (_showControls) + _buildControls(title), + ], + ), + ), + ); + } + + Widget _buildControls(String title) { + return Stack( + children: [ + // Top Bar + Positioned( + top: 0, left: 0, right: 0, + child: Container( + color: Colors.black54, + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Row( + children: [ + TVFocusable( + focusNode: _backFocusNode, + onPressed: () => Navigator.pop(context), + child: const Icon(Icons.arrow_back, color: Colors.white), + ), + const SizedBox(width: 16), + // Icon + if (widget.channels != null && widget.channels![_currentIndex].streamIcon.isNotEmpty) + Padding( + padding: const EdgeInsets.only(right: 12), + child: SizedBox( + width: 32, + height: 32, + child: CachedNetworkImage( + imageUrl: widget.channels![_currentIndex].streamIcon, + errorWidget: (_,__,___) => const SizedBox.shrink(), + ), + ), + ), + Text('LITE PLAYER: $title', style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), + const Spacer(), + Text(_currentTime, style: const TextStyle(color: Colors.white70)), + ], + ), + ), + ), + + // Center Controls + Center( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.streamType == StreamType.live) ...[ + IconButton( + icon: const Icon(Icons.keyboard_arrow_up, color: Colors.white, size: 40), + onPressed: _playPrevious, + ), + const SizedBox(width: 32), + ] else ...[ + IconButton( + icon: const Icon(Icons.replay_10, color: Colors.white, size: 40), + onPressed: () => _seek(const Duration(seconds: -10)), + ), + const SizedBox(width: 32), + ], + + TVFocusable( + focusNode: _playPauseFocusNode, + onPressed: _togglePlayPause, + child: Icon( + _isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled, + color: AppColors.primary, + size: 64, + ), + ), + + if (widget.streamType == StreamType.live) ...[ + const SizedBox(width: 32), + IconButton( + icon: const Icon(Icons.keyboard_arrow_down, color: Colors.white, size: 40), + onPressed: _playNext, + ), + ] else ...[ + const SizedBox(width: 32), + IconButton( + icon: const Icon(Icons.forward_10, color: Colors.white, size: 40), + onPressed: () => _seek(const Duration(seconds: 10)), + ), + ], + ], + ), + ), + + // EPG Content (Bottom Left) + if (widget.streamType == StreamType.live && _epg != null && _epg!.nowPlaying != null) + Positioned( + bottom: 80, // Above progress/bottom bar + left: 24, + width: 350, + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.7), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.white24), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _epg!.nowPlaying!, + style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + if (_epg!.nextPlaying != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + "A suivre: ${_epg!.nextPlaying}", + style: const TextStyle(color: Colors.white70, fontSize: 14), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + // LIVE Badge + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + margin: const EdgeInsets.only(left: 8), + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(4), + ), + child: const Text('LIVE', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12)), + ), + ], + ), + ), + ), + + // Progress Bar (Bottom) - Only for VOD + if (widget.streamType != StreamType.live) + Positioned( + bottom: 0, left: 0, right: 0, + child: Container( + color: Colors.black54, + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), + child: Row( + children: [ + Text(_formatDuration(_position), style: const TextStyle(color: Colors.white)), + Expanded( + child: Slider( + value: _position.inSeconds.toDouble().clamp(0, _duration.inSeconds.toDouble()), + min: 0, + max: _duration.inSeconds.toDouble(), + activeColor: AppColors.primary, + inactiveColor: Colors.white24, + onChanged: (val) { + setState(() { + _position = Duration(seconds: val.toInt()); + _isSeeking = true; + }); + }, + onChangeEnd: (val) { + _controller?.seekTo(Duration(seconds: val.toInt())); + _isSeeking = false; + _onUserInteraction(); + }, + ), + ), + Text(_formatDuration(_duration), style: const TextStyle(color: Colors.white)), + ], + ), + ), + ), + ], + ); + } +} diff --git a/lib/mobile/features/iptv/screens/mobile_playlist_selection_screen.dart b/lib/mobile/features/iptv/screens/mobile_playlist_selection_screen.dart index d6bbc3f..5ecf1e8 100644 --- a/lib/mobile/features/iptv/screens/mobile_playlist_selection_screen.dart +++ b/lib/mobile/features/iptv/screens/mobile_playlist_selection_screen.dart @@ -13,77 +13,130 @@ final playlistsProvider = FutureProvider>((ref) async { return service.getPlaylists(); }); -class MobilePlaylistSelectionScreen extends ConsumerWidget { - const MobilePlaylistSelectionScreen({super.key}); +class MobilePlaylistSelectionScreen extends ConsumerStatefulWidget { + final bool manageMode; + const MobilePlaylistSelectionScreen({super.key, this.manageMode = false}); @override - Widget build(BuildContext context, WidgetRef ref) { + ConsumerState createState() => _MobilePlaylistSelectionScreenState(); +} + +class _MobilePlaylistSelectionScreenState extends ConsumerState { + @override + void initState() { + super.initState(); + if (!widget.manageMode) { + // Check for auto-login after build + WidgetsBinding.instance.addPostFrameCallback((_) { + _checkAutoLogin(); + }); + } + } + + Future _checkAutoLogin() async { + final playlists = await ref.read(playlistsProvider.future); + if (playlists.isNotEmpty && mounted) { + // Auto-login to the first playlist (or last used) + // Ideally last used, but for now first is fine as per request "une playlist existe". + context.go('/dashboard', extra: playlists.first); + } + } + + @override + Widget build(BuildContext context) { final currentUser = ref.watch(authProvider).currentUser; final playlistsAsync = ref.watch(playlistsProvider); return Theme( data: MobileTheme.darkTheme, child: Scaffold( + extendBodyBehindAppBar: true, // For gradient appBar: AppBar( - title: const Text('Playlists'), + title: Text(widget.manageMode ? 'Gérer les Playlists' : 'Playlists'), + backgroundColor: Colors.transparent, + elevation: 0, actions: [ - IconButton( - icon: const Icon(Icons.logout), - onPressed: () async { - await ref.read(authProvider.notifier).logout(); - if (context.mounted) { - context.go('/login'); - } - }, - ), + if (widget.manageMode) + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(context), + ), ], ), - body: playlistsAsync.when( - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, stack) => Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.error_outline, size: 48, color: AppColors.error), - const SizedBox(height: 16), - Text('Error loading playlists', style: GoogleFonts.inter()), - TextButton( - onPressed: () => ref.refresh(playlistsProvider), - child: const Text('Retry'), - ), - ], - ), + body: Container( + decoration: const BoxDecoration( + gradient: AppColors.appleTvGradient, ), - data: (playlists) { - if (playlists.isEmpty) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.playlist_remove, size: 48, color: AppColors.textSecondary), - const SizedBox(height: 16), - Text('No playlists available', style: GoogleFonts.inter(color: AppColors.textSecondary)), - ], - ), - ); - } + child: playlistsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, stack) => Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline, size: 48, color: AppColors.error), + const SizedBox(height: 16), + Text('Erreur de chargement', style: GoogleFonts.inter(color: Colors.white)), + TextButton( + onPressed: () => ref.refresh(playlistsProvider), + child: const Text('Réessayer'), + ), + ], + ), + ), + data: (playlists) { + if (playlists.isEmpty) { + // Even in auto-mode, if empty we show this (or add button) + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.playlist_add, size: 64, color: Colors.white54), + const SizedBox(height: 24), + Text( + 'Aucune playlist configurée', + style: GoogleFonts.inter(fontSize: 18, color: Colors.white70), + ), + const SizedBox(height: 32), + ElevatedButton.icon( + onPressed: () { + // Logic to add playlist (usually dialog or separate screen) + // specific logic for add playlist + }, + icon: const Icon(Icons.add), + label: const Text('Ajouter une Playlist'), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: Colors.black, + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + ), + ), + ], + ), + ); + } - return ListView.separated( - padding: const EdgeInsets.all(16), - itemCount: playlists.length, - separatorBuilder: (context, index) => const SizedBox(height: 16), - itemBuilder: (context, index) { - final playlist = playlists[index]; - return _MobilePlaylistCard( - playlist: playlist, - onTap: () { - // Mobile navigation to dashboard with playlist - context.go('/dashboard', extra: playlist); - }, - ); - }, - ); - }, + return ListView.separated( + padding: const EdgeInsets.fromLTRB(16, 100, 16, 16), // Top padding for AppBar + itemCount: playlists.length, + separatorBuilder: (context, index) => const SizedBox(height: 16), + itemBuilder: (context, index) { + final playlist = playlists[index]; + return _MobilePlaylistCard( + playlist: playlist, + onTap: () { + if (widget.manageMode) { + // In manage mode, maybe we want to edit or delete? + // For now, just switch to it. + context.go('/dashboard', extra: playlist); + } else { + context.go('/dashboard', extra: playlist); + } + }, + ); + }, + ); + }, + ), ), ), ); diff --git a/lib/mobile/features/iptv/screens/mobile_series_detail_screen.dart b/lib/mobile/features/iptv/screens/mobile_series_detail_screen.dart index 1c5f8d1..71d8158 100644 --- a/lib/mobile/features/iptv/screens/mobile_series_detail_screen.dart +++ b/lib/mobile/features/iptv/screens/mobile_series_detail_screen.dart @@ -4,6 +4,7 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:google_fonts/google_fonts.dart'; import '../../../../core/models/playlist_config.dart'; import '../../../../features/iptv/models/xtream_models.dart'; +import 'package:xtremflow/mobile/features/iptv/screens/lite_player_screen.dart'; import '../../../providers/mobile_xtream_providers.dart'; import '../../../providers/mobile_settings_providers.dart'; import 'native_player_screen.dart'; @@ -104,7 +105,7 @@ class _MobileSeriesDetailScreenState extends ConsumerState NativePlayerScreen( - streamId: episode.id, - title: '${widget.series.name} - ${episode.title}', - playlist: widget.playlist, - streamType: StreamType.series, - containerExtension: episode.containerExtension ?? 'mkv', - seriesId: widget.series.seriesId, - season: _selectedSeason, - episodeNum: episode.episodeNum, - ), - ), - ); + final engine = ref.read(mobileSettingsProvider).playerEngine; + + if (engine == 'lite') { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => LitePlayerScreen( + streamId: episode.streamId, + title: "${widget.series.name} S${episode.seasonNum}E${episode.episodeNum}", + playlist: widget.playlist, + streamType: StreamType.series, + containerExtension: episode.containerExtension ?? 'mp4', + seriesId: widget.series.seriesId, + season: episode.seasonNum, + episodeNum: episode.episodeNum, + ), + ), + ); + } else { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => NativePlayerScreen( + streamId: episode.streamId, + title: "${widget.series.name} S${episode.seasonNum}E${episode.episodeNum}", + playlist: widget.playlist, + streamType: StreamType.series, + containerExtension: episode.containerExtension ?? 'mp4', + seriesId: widget.series.seriesId, + season: episode.seasonNum, + episodeNum: episode.episodeNum, + ), + ), + ); + } }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), diff --git a/lib/mobile/features/iptv/screens/native_player_screen.dart b/lib/mobile/features/iptv/screens/native_player_screen.dart index d02561a..bf0e1b1 100644 --- a/lib/mobile/features/iptv/screens/native_player_screen.dart +++ b/lib/mobile/features/iptv/screens/native_player_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:media_kit/media_kit.dart'; import 'package:media_kit_video/media_kit_video.dart'; +import 'package:xtremflow/mobile/widgets/tv_focusable.dart'; import 'package:path_provider/path_provider.dart'; import 'package:xtremflow/core/models/iptv_models.dart'; import 'package:xtremflow/core/models/playlist_config.dart'; @@ -54,6 +55,13 @@ class NativePlayerScreen extends ConsumerStatefulWidget { class _NativePlayerScreenState extends ConsumerState with WidgetsBindingObserver { late final Player _player; late final VideoController _controller; + + // Focus Nodes + final FocusNode _playPauseFocusNode = FocusNode(); + final FocusNode _prevFocusNode = FocusNode(); + final FocusNode _nextFocusNode = FocusNode(); + final FocusNode _backFocusNode = FocusNode(); + bool _isLoading = true; String? _errorMessage; late int _currentIndex; @@ -73,12 +81,16 @@ class _NativePlayerScreenState extends ConsumerState with Wi String _currentTime = ''; bool _hasMarkedAsWatched = false; // Flag to mark watched only once at 80% + + void _resetControlsTimer() { _controlsTimer?.cancel(); + _startClock(); // Ensure clock runs when controls are shown if (_showControls && _isPlaying) { _controlsTimer = Timer(const Duration(seconds: 10), () { if (mounted) { setState(() => _showControls = false); + _stopClock(); // Save CPU when hidden } }); } @@ -113,29 +125,37 @@ class _NativePlayerScreenState extends ConsumerState with Wi _player = Player(configuration: config); // Enable software decoding fallback if hardware fails (handled by mpv usually, but ensuring 'auto' helps) - (_player.platform as dynamic)?.setProperty('hwdec', 'auto'); + final decoderMode = ref.read(mobileSettingsProvider).decoderMode; + (_player.platform as dynamic)?.setProperty('hwdec', decoderMode); + debugPrint('MediaKitPlayer: Decoder Mode set to $decoderMode'); - // ============ OPTIMIZED STREAM STABILITY CONFIGURATION ============ - // Aggressive buffering and reconnection for stable live TV playback + // ============ PERFORMANCE 2.0 (LOW MEMORY 1GB PROFILE) ============ + // Tuned for Low-End Android TV hardware (1GB RAM Sticks) + // Goal: Prevent OOM Kills & Crashes - // Large cache for smooth playback + // 50MB Cache = ~1 min of HD stream. Critical for 1GB RAM. (_player.platform as dynamic)?.setProperty('cache', 'yes'); - (_player.platform as dynamic)?.setProperty('cache-secs', '300'); // Cache up to 5 minutes - (_player.platform as dynamic)?.setProperty('demuxer-max-bytes', '150000000'); // 150MB max buffer - (_player.platform as dynamic)?.setProperty('demuxer-max-back-bytes', '75000000'); // 75MB back buffer - (_player.platform as dynamic)?.setProperty('cache-pause-initial', 'yes'); // Wait for cache before playing - (_player.platform as dynamic)?.setProperty('cache-pause-wait', '5'); // Wait 5s minimum cache + (_player.platform as dynamic)?.setProperty('cache-secs', '60'); // 1 minute cache + (_player.platform as dynamic)?.setProperty('demuxer-max-bytes', '50000000'); // 50MB buffer + (_player.platform as dynamic)?.setProperty('demuxer-max-back-bytes', '10000000'); // 10MB back buffer + (_player.platform as dynamic)?.setProperty('cache-pause-initial', 'yes'); + (_player.platform as dynamic)?.setProperty('cache-pause-wait', '3'); // Shorter wait to start + + // Standard Processing (Hardware handles it) + (_player.platform as dynamic)?.setProperty('video-sync', 'audio'); + (_player.platform as dynamic)?.setProperty('interpolation', 'no'); // Keep off for safety + (_player.platform as dynamic)?.setProperty('audio-buffer', '0.5'); // Standard audio buffer // Network resilience - (_player.platform as dynamic)?.setProperty('network-timeout', '120'); // 2 minute timeout - (_player.platform as dynamic)?.setProperty('stream-timeout', '120'); // 2 minute stream timeout - (_player.platform as dynamic)?.setProperty('tls-verify', 'no'); // Ignore SSL errors + (_player.platform as dynamic)?.setProperty('network-timeout', '120'); + (_player.platform as dynamic)?.setProperty('stream-timeout', '120'); + (_player.platform as dynamic)?.setProperty('tls-verify', 'no'); (_player.platform as dynamic)?.setProperty('http-header-fields', 'User-Agent: XtremFlow/1.0'); - // Aggressive reconnection for live streams - (_player.platform as dynamic)?.setProperty('stream-lavf-o', 'reconnect=1,reconnect_streamed=1,reconnect_on_network_error=1,reconnect_on_http_error=4xx,reconnect_delay_max=10'); + // Live Stream optimizations + (_player.platform as dynamic)?.setProperty('stream-lavf-o', 'reconnect=1,reconnect_streamed=1,reconnect_on_network_error=1,reconnect_delay_max=5'); (_player.platform as dynamic)?.setProperty('force-seekable', 'yes'); - (_player.platform as dynamic)?.setProperty('demuxer-lavf-o', 'live_start_index=-1,analyzeduration=10000000,probesize=10000000'); + (_player.platform as dynamic)?.setProperty('demuxer-lavf-o', 'live_start_index=-1'); // Removed large probesize // Prevent stalls (_player.platform as dynamic)?.setProperty('demuxer-readahead-secs', '60'); // Read 60s ahead @@ -223,10 +243,16 @@ class _NativePlayerScreenState extends ConsumerState with Wi } void _startClock() { + if (_clockTimer != null && _clockTimer!.isActive) return; _updateTime(); _clockTimer = Timer.periodic(const Duration(seconds: 1), (_) => _updateTime()); } + void _stopClock() { + _clockTimer?.cancel(); + _clockTimer = null; + } + void _updateTime() { if (mounted) { final now = DateTime.now(); @@ -272,6 +298,12 @@ class _NativePlayerScreenState extends ConsumerState with Wi ]); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + // Dispose focus nodes + _playPauseFocusNode.dispose(); + _prevFocusNode.dispose(); + _nextFocusNode.dispose(); + _backFocusNode.dispose(); + super.dispose(); } @@ -475,7 +507,13 @@ class _NativePlayerScreenState extends ConsumerState with Wi // Enable software decoding fallback if hardware fails (handled by mpv usually, but ensuring 'auto' helps) // If we are in fallback mode, force software ('no') - (_player.platform as dynamic)?.setProperty('hwdec', _useSoftwareDecoder ? 'no' : 'auto'); + String hwdecValue; + if (_useSoftwareDecoder) { + hwdecValue = 'no'; + } else { + hwdecValue = ref.read(mobileSettingsProvider).decoderMode; + } + (_player.platform as dynamic)?.setProperty('hwdec', hwdecValue); await _player.open( Media(streamUrl, httpHeaders: {'User-Agent': 'XtremFlow/1.0'}), @@ -566,6 +604,11 @@ class _NativePlayerScreenState extends ConsumerState with Wi // Always show controls on tap, then start auto-hide timer if (!_showControls) { setState(() => _showControls = true); + // Request focus on Play/Pause button when opening + WidgetsBinding.instance.addPostFrameCallback((_) { + // If controls opened, default to Play/Pause + _playPauseFocusNode.requestFocus(); + }); } _resetControlsTimer(); } @@ -576,16 +619,37 @@ class _NativePlayerScreenState extends ConsumerState with Wi final key = event.logicalKey; - // Space / Enter / Select - Toggle play/pause + // Space / Enter / Select if (key == LogicalKeyboardKey.space || key == LogicalKeyboardKey.enter || - key == LogicalKeyboardKey.select) { - _togglePlayPause(); - return true; + key == LogicalKeyboardKey.select || + key == LogicalKeyboardKey.numpadEnter || + key == LogicalKeyboardKey.gameButtonA) { + // If controls are hidden, toggle them + play/pause + if (!_showControls) { + _togglePlayPause(); + _toggleControls(); + return true; + } + // If controls are visible, let Focus system handle button press + return false; + } + + // Debug Toggle: Long Press Key 'D' or 0 (if mapped) - Simplified to just a secret key combo? + // Let's use a long-press logic on Select in _handleKeyEvent? + // Actually, handling long press in key down is hard. + // We'll add a 'Debug' button in the settings or just map Key '0' if remote has it. + // Debug Toggle: Long Press Key 'D' or 0 (if mapped) + if (key == LogicalKeyboardKey.digit0) { + final current = ref.read(mobileSettingsProvider).showDebugStats; + ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(!current); + return true; } // Left Arrow - Seek back 10 seconds if (key == LogicalKeyboardKey.arrowLeft) { + if (_showControls) return false; // Let Focus handle navigation + if (widget.streamType != StreamType.live) { final newPos = _position - const Duration(seconds: 10); _player.seek(newPos < Duration.zero ? Duration.zero : newPos); @@ -596,6 +660,8 @@ class _NativePlayerScreenState extends ConsumerState with Wi // Right Arrow - Seek forward 10 seconds if (key == LogicalKeyboardKey.arrowRight) { + if (_showControls) return false; // Let Focus handle navigation + if (widget.streamType != StreamType.live) { final newPos = _position + const Duration(seconds: 10); if (newPos < _duration) { @@ -625,7 +691,12 @@ class _NativePlayerScreenState extends ConsumerState with Wi // Escape / Back - Exit player if (key == LogicalKeyboardKey.escape || key == LogicalKeyboardKey.goBack) { - Navigator.of(context).pop(); + // If controls are visible, close them first + if (_showControls) { + setState(() => _showControls = false); + } else { + Navigator.of(context).pop(); + } return true; } @@ -683,22 +754,33 @@ class _NativePlayerScreenState extends ConsumerState with Wi child: SafeArea( child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - gradient: LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [ - Colors.black.withOpacity(0.8), - Colors.transparent, - ], - ), + decoration: const BoxDecoration( + color: Colors.black54, // Flat color instead of Gradient for performance ), child: Row( children: [ // Main Back Button - IconButton( - icon: const Icon(Icons.arrow_back, color: Colors.white), - onPressed: () => Navigator.pop(context), + // Main Back Button + TVFocusable( + focusNode: _backFocusNode, + onPressed: () => Navigator.pop(context), + onFocus: _resetControlsTimer, + borderRadius: BorderRadius.circular(50), + child: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + ), + // Hidden Debug Trigger (Invisible InkWell next to back button) + InkWell( + onLongPress: () { + final current = ref.read(mobileSettingsProvider).showDebugStats; + ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(!current); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Debug Mode: ${!current ? "ON" : "OFF"}'), duration: const Duration(seconds: 1)), + ); + }, + child: const SizedBox(width: 20, height: 40), ), Expanded( child: Column( @@ -734,12 +816,20 @@ class _NativePlayerScreenState extends ConsumerState with Wi ), ), ), + + // Stats Overlay (Top Left) - Isolated to prevent main rebuilds + Positioned( + top: 80, + left: 16, + child: StatsOverlayWidget(player: _player), + ), ], ), ), ); } + String _formatDuration(Duration duration) { String twoDigits(int n) => n.toString().padLeft(2, '0'); String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); @@ -763,46 +853,85 @@ class _NativePlayerScreenState extends ConsumerState with Wi children: [ // Prev Channel / Replay 10s if (widget.streamType == StreamType.live && widget.channels != null && widget.channels!.isNotEmpty) - IconButton( - icon: const Icon(Icons.skip_previous, color: Colors.white, size: 48), + TVFocusable( + focusNode: _prevFocusNode, onPressed: _playPrevious, + onFocus: _resetControlsTimer, + borderRadius: BorderRadius.circular(50), + child: IconButton( + icon: const Icon(Icons.skip_previous, color: Colors.white, size: 48), + onPressed: _playPrevious, + ), ) else if (widget.streamType != StreamType.live) - IconButton( - icon: const Icon(Icons.replay_10, color: Colors.white, size: 48), + TVFocusable( + focusNode: _prevFocusNode, onPressed: () async { final pos = await _player.stream.position.first; _player.seek(pos - const Duration(seconds: 10)); + _resetControlsTimer(); }, + onFocus: _resetControlsTimer, + borderRadius: BorderRadius.circular(50), + child: IconButton( + icon: const Icon(Icons.replay_10, color: Colors.white, size: 48), + onPressed: () async { + final pos = await _player.stream.position.first; + _player.seek(pos - const Duration(seconds: 10)); + }, + ), ), const SizedBox(width: 32), // Play/Pause - IconButton( - iconSize: 72, - icon: Icon( - _isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled, - color: Colors.white, - ), + TVFocusable( + focusNode: _playPauseFocusNode, onPressed: _togglePlayPause, + onFocus: _resetControlsTimer, + scale: 1.1, // Larger scale for main button + borderRadius: BorderRadius.circular(50), + child: IconButton( + iconSize: 72, + icon: Icon( + _isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled, + color: Colors.white, + ), + onPressed: _togglePlayPause, + ), ), const SizedBox(width: 32), // Next Channel / Forward 10s if (widget.streamType == StreamType.live && widget.channels != null && widget.channels!.isNotEmpty) - IconButton( - icon: const Icon(Icons.skip_next, color: Colors.white, size: 48), + TVFocusable( + focusNode: _nextFocusNode, onPressed: _playNext, + onFocus: _resetControlsTimer, + borderRadius: BorderRadius.circular(50), + child: IconButton( + icon: const Icon(Icons.skip_next, color: Colors.white, size: 48), + onPressed: _playNext, + ), ) else if (widget.streamType != StreamType.live) - IconButton( - icon: const Icon(Icons.forward_10, color: Colors.white, size: 48), + TVFocusable( + focusNode: _nextFocusNode, onPressed: () async { final pos = await _player.stream.position.first; _player.seek(pos + const Duration(seconds: 10)); + _resetControlsTimer(); }, + onFocus: _resetControlsTimer, + borderRadius: BorderRadius.circular(50), + child: IconButton( + icon: const Icon(Icons.forward_10, color: Colors.white, size: 48), + onPressed: () async { + final pos = await _player.stream.position.first; + _player.seek(pos + const Duration(seconds: 10)); + }, + ), ), ], ), @@ -1015,3 +1144,70 @@ class _NativePlayerScreenState extends ConsumerState with Wi ); } } + +/// Isolated Stats Widget to prevent rebuilding the entire Video Player on every update +class StatsOverlayWidget extends ConsumerStatefulWidget { + final Player player; + const StatsOverlayWidget({super.key, required this.player}); + + @override + ConsumerState createState() => _StatsOverlayWidgetState(); +} + +class _StatsOverlayWidgetState extends ConsumerState { + Duration _buffer = Duration.zero; + String _decoder = 'Unknown'; + + // Throttling updates + Timer? _updateTimer; + + @override + void initState() { + super.initState(); + // Use a periodic timer to poll/update stats instead of listening to every single frequent event + // This reduces UI thread load significantly on low-end devices + _updateTimer = Timer.periodic(const Duration(milliseconds: 1000), (_) { + if (mounted) { + setState(() { + _buffer = widget.player.state.buffer; + // Accessing nested prop safely just in case + final track = widget.player.state.track.video; + _decoder = track.decoder ?? 'Auto'; + }); + } + }); + } + + @override + void dispose() { + _updateTimer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (!ref.watch(mobileSettingsProvider).showDebugStats) return const SizedBox.shrink(); + + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.7), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.green.withOpacity(0.5)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text('STATS FOR NERDS 🤓', + style: TextStyle(color: Colors.green, fontWeight: FontWeight.bold, fontSize: 12)), + const SizedBox(height: 4), + Text('Buffer: ${_buffer.inSeconds}s', + style: const TextStyle(color: Colors.white, fontSize: 12)), + Text('Decoder: $_decoder', + style: const TextStyle(color: Colors.white, fontSize: 12)), + ], + ), + ); + } +} diff --git a/lib/mobile/features/iptv/widgets/mobile_live_tv_tab.dart b/lib/mobile/features/iptv/widgets/mobile_live_tv_tab.dart index 5c3c1e7..d494913 100644 --- a/lib/mobile/features/iptv/widgets/mobile_live_tv_tab.dart +++ b/lib/mobile/features/iptv/widgets/mobile_live_tv_tab.dart @@ -11,6 +11,9 @@ import '../../../../core/models/playlist_config.dart'; import '../../../../core/theme/app_colors.dart'; import '../../../../core/api/dns_resolver.dart'; import '../../../theme/mobile_theme.dart'; +import 'package:xtremflow/mobile/widgets/tv_focusable.dart'; +import 'package:xtremflow/mobile/features/iptv/screens/lite_player_screen.dart'; +import 'package:flutter/services.dart'; class MobileLiveTVTab extends ConsumerStatefulWidget { final PlaylistConfig playlist; @@ -21,10 +24,13 @@ class MobileLiveTVTab extends ConsumerStatefulWidget { } class _MobileLiveTVTabState extends ConsumerState with AutomaticKeepAliveClientMixin { - String? _selectedCategory; + + final TextEditingController _searchController = TextEditingController(); + final FocusNode _searchFocusNode = FocusNode(); String _searchQuery = ''; bool _showFavoritesOnly = false; + bool _isSearchEditing = false; @override void initState() { @@ -39,10 +45,12 @@ class _MobileLiveTVTabState extends ConsumerState with Automati @override void dispose() { _searchController.dispose(); + _searchFocusNode.dispose(); super.dispose(); } - bool _isCategoryView = true; + + @override bool get wantKeepAlive => true; @@ -53,10 +61,30 @@ class _MobileLiveTVTabState extends ConsumerState with Automati final channelsAsync = ref.watch(mobileLiveChannelsProvider(widget.playlist)); final favorites = ref.watch(mobileFavoritesProvider); final settings = ref.watch(mobileSettingsProvider); + final uiState = ref.watch(mobileLiveTvUiStateProvider); + final uiNotifier = ref.read(mobileLiveTvUiStateProvider.notifier); - return Scaffold( - backgroundColor: AppColors.background, - body: channelsAsync.when( + return Container( + decoration: const BoxDecoration(gradient: AppColors.appleTvGradient), + child: Scaffold( + backgroundColor: Colors.transparent, + body: PopScope( + canPop: uiState.isCategoryView && _searchQuery.isEmpty && !_showFavoritesOnly, + onPopInvoked: (didPop) { + if (didPop) return; + + if (_searchQuery.isNotEmpty) { + setState(() { + _searchController.clear(); + _searchQuery = ''; + }); + } else if (_showFavoritesOnly) { + setState(() => _showFavoritesOnly = false); + } else if (!uiState.isCategoryView) { + uiNotifier.state = uiState.copyWith(isCategoryView: true); + } + }, + child: channelsAsync.when( loading: () => const Center(child: CircularProgressIndicator()), error: (e, s) => Center( child: Padding( @@ -80,7 +108,7 @@ class _MobileLiveTVTabState extends ConsumerState with Automati List displayedChannels = []; // Determine mode based on search/favorites/selection - bool showGrid = _isCategoryView && _searchQuery.isEmpty && !_showFavoritesOnly; + bool showGrid = uiState.isCategoryView && _searchQuery.isEmpty && !_showFavoritesOnly; if (!showGrid) { if (_searchQuery.isNotEmpty) { @@ -91,8 +119,8 @@ class _MobileLiveTVTabState extends ConsumerState with Automati displayedChannels = groupedChannels.values.expand((l) => l) .where((c) => favorites.contains(c.streamId)) .toList(); - } else if (_selectedCategory != null) { - displayedChannels = groupedChannels[_selectedCategory] ?? []; + } else if (uiState.selectedCategory != null) { + displayedChannels = groupedChannels[uiState.selectedCategory] ?? []; } } @@ -106,34 +134,49 @@ class _MobileLiveTVTabState extends ConsumerState with Automati child: Column( children: [ // Search Bar - Container( - height: 48, - decoration: BoxDecoration( - color: AppColors.surface, - borderRadius: BorderRadius.circular(12), - ), - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - const Icon(Icons.search, color: AppColors.textSecondary), - const SizedBox(width: 8), - Expanded( - child: TextField( - controller: _searchController, - style: const TextStyle(color: AppColors.textPrimary), - decoration: const InputDecoration( - hintText: 'Rechercher une chaîne...', - border: InputBorder.none, - isDense: true, + GestureDetector( + onTap: () { + setState(() => _isSearchEditing = true); + WidgetsBinding.instance.addPostFrameCallback((_) { + _searchFocusNode.requestFocus(); + }); + }, + child: Container( + height: 48, + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: BorderRadius.circular(12), + border: _isSearchEditing ? Border.all(color: AppColors.primary) : null, + ), + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + const Icon(Icons.search, color: AppColors.textSecondary), + const SizedBox(width: 8), + Expanded( + child: ExcludeFocus( + excluding: !_isSearchEditing, + child: TextField( + controller: _searchController, + focusNode: _searchFocusNode, + readOnly: !_isSearchEditing, + style: const TextStyle(color: AppColors.textPrimary), + decoration: const InputDecoration( + hintText: 'Rechercher une chaîne...', + border: InputBorder.none, + isDense: true, + ), + onSubmitted: (_) => setState(() => _isSearchEditing = false), + ), ), ), - ), - if (_searchQuery.isNotEmpty) - GestureDetector( - onTap: () => _searchController.clear(), - child: const Icon(Icons.close, color: AppColors.textSecondary), - ), - ], + if (_searchQuery.isNotEmpty) + GestureDetector( + onTap: () => _searchController.clear(), + child: const Icon(Icons.close, color: AppColors.textSecondary), + ), + ], + ), ), ), @@ -151,7 +194,7 @@ class _MobileLiveTVTabState extends ConsumerState with Automati } else if (_showFavoritesOnly) { setState(() => _showFavoritesOnly = false); } else { - setState(() => _isCategoryView = true); + uiNotifier.state = uiState.copyWith(isCategoryView: true); } }, padding: EdgeInsets.zero, @@ -164,7 +207,7 @@ class _MobileLiveTVTabState extends ConsumerState with Automati _searchQuery.isNotEmpty ? 'Résultats de recherche' : _showFavoritesOnly ? 'Favoris' : showGrid ? 'Catégories' : - _selectedCategory ?? 'Chaînes', + uiState.selectedCategory ?? 'Chaînes', style: const TextStyle( color: AppColors.textPrimary, fontWeight: FontWeight.bold, @@ -181,9 +224,9 @@ class _MobileLiveTVTabState extends ConsumerState with Automati onPressed: () => setState(() { _showFavoritesOnly = !_showFavoritesOnly; // Reset category view if entering favorites - if (_showFavoritesOnly) _isCategoryView = false; + if (_showFavoritesOnly) uiNotifier.state = uiState.copyWith(isCategoryView: false); // If exiting favorites, default depends on logic (here back to category grid if was previously) - if (!_showFavoritesOnly) _isCategoryView = true; + if (!_showFavoritesOnly) uiNotifier.state = uiState.copyWith(isCategoryView: true); }), ), ], @@ -203,6 +246,8 @@ class _MobileLiveTVTabState extends ConsumerState with Automati ); }, ), + ), + ), ); } @@ -227,12 +272,12 @@ class _MobileLiveTVTabState extends ConsumerState with Automati itemCount: categories.length, itemBuilder: (context, index) { final category = categories[index]; - return InkWell( - onTap: () { - setState(() { - _selectedCategory = category; - _isCategoryView = false; - }); + return TVFocusable( + onPressed: () { + ref.read(mobileLiveTvUiStateProvider.notifier).state = LiveTvUiState( + selectedCategory: category, + isCategoryView: false, + ); }, borderRadius: BorderRadius.circular(16), child: Container( @@ -303,25 +348,44 @@ class _MobileLiveTVTabState extends ConsumerState with Automati return _MobileChannelTile( channel: channel, playlist: widget.playlist, - onTap: () => _playChannel(context, channel, channels), + onTap: () => _playChannel(context, channel, channels, widget.playlist, index), ); }, ); } - void _playChannel(BuildContext context, Channel channel, List channels) { - Navigator.of(context).push( - MaterialPageRoute( - builder: (context) => NativePlayerScreen( - streamId: channel.streamId, - title: channel.name, - playlist: widget.playlist, - streamType: StreamType.live, - channels: channels, - initialIndex: channels.indexOf(channel), - ), - ), - ); + void _playChannel(BuildContext context, Channel channel, List channels, PlaylistConfig playlist, int index) { + final engine = ref.read(mobileSettingsProvider).playerEngine; + + if (engine == 'lite') { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => LitePlayerScreen( + streamId: channel.streamId, + title: channel.name, + playlist: playlist, + streamType: StreamType.live, + channels: channels, // Pass full channel list for zapping + initialIndex: index, + ), + ), + ); + } else { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => NativePlayerScreen( + streamId: channel.streamId, + title: channel.name, + playlist: playlist, + streamType: StreamType.live, + channels: channels, // Pass full channel list for zapping + initialIndex: index, + ), + ), + ); + } } } @@ -375,8 +439,8 @@ class _MobileChannelTileState extends ConsumerState<_MobileChannelTile> { final favorites = ref.watch(mobileFavoritesProvider); final isFavorite = favorites.contains(widget.channel.streamId); - return InkWell( - onTap: widget.onTap, + return TVFocusable( + onPressed: widget.onTap, borderRadius: BorderRadius.circular(12), child: Container( padding: const EdgeInsets.all(8), diff --git a/lib/mobile/features/iptv/widgets/mobile_movies_tab.dart b/lib/mobile/features/iptv/widgets/mobile_movies_tab.dart index 883810e..90a63e8 100644 --- a/lib/mobile/features/iptv/widgets/mobile_movies_tab.dart +++ b/lib/mobile/features/iptv/widgets/mobile_movies_tab.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:xtremflow/mobile/widgets/tv_focusable.dart'; import '../../../../core/models/playlist_config.dart'; import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/components/hero_carousel.dart'; @@ -9,6 +11,7 @@ import '../../../providers/mobile_settings_providers.dart'; import '../../../providers/mobile_xtream_providers.dart'; import '../../../../features/iptv/services/xtream_service_mobile.dart'; import '../screens/native_player_screen.dart'; +import '../screens/lite_player_screen.dart'; class MobileMoviesTab extends ConsumerStatefulWidget { final PlaylistConfig playlist; @@ -21,9 +24,11 @@ class MobileMoviesTab extends ConsumerStatefulWidget { class _MobileMoviesTabState extends ConsumerState with AutomaticKeepAliveClientMixin { final ScrollController _scrollController = ScrollController(); final TextEditingController _searchController = TextEditingController(); + final FocusNode _searchFocusNode = FocusNode(); final List _movies = []; List? _searchResults; String _searchQuery = ''; + bool _isSearchEditing = false; bool _isLoading = false; bool _isSearching = false; bool _hasMore = true; @@ -42,6 +47,7 @@ class _MobileMoviesTabState extends ConsumerState with Automati void dispose() { _scrollController.dispose(); _searchController.dispose(); + _searchFocusNode.dispose(); _searchDebounce?.cancel(); super.dispose(); } @@ -159,20 +165,38 @@ class _MobileMoviesTabState extends ConsumerState with Automati return originalUrl; } - void _playMovie(Movie movie) { - // Watch progress is tracked in player at 80% completion - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => NativePlayerScreen( - streamId: movie.streamId, - title: movie.name, - playlist: widget.playlist, - streamType: StreamType.vod, - containerExtension: movie.containerExtension ?? 'mp4', + void _playMovie(BuildContext context, Movie movie) { + if (widget.playlist == null) return; + + final engine = ref.read(mobileSettingsProvider).playerEngine; + + if (engine == 'lite') { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => LitePlayerScreen( + streamId: movie.streamId, + title: movie.name, + playlist: widget.playlist!, + streamType: StreamType.vod, + containerExtension: movie.containerExtension, + ), ), - ), - ); + ); + } else { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => NativePlayerScreen( + streamId: movie.streamId, + title: movie.name, + playlist: widget.playlist!, + streamType: StreamType.vod, + containerExtension: movie.containerExtension, + ), + ), + ); + } } @override @@ -198,131 +222,153 @@ class _MobileMoviesTabState extends ConsumerState with Automati id: m.streamId, title: m.name, imageUrl: _getImageUrl(m.streamIcon), - subtitle: m.rating != null ? '${_formatRating(m.rating)} ★' : null, - onMoreInfo: () => _playMovie(m), - )).toList(); + subtitle: m.rating != null ? '${_formatRating(m.rating)} ★' : null, + onMoreInfo: () => _playMovie(context, m), + )).toList(); - return SafeArea( - bottom: false, - child: RefreshIndicator( - onRefresh: _refresh, - color: AppColors.primary, - backgroundColor: AppColors.surface, - child: CustomScrollView( - controller: _scrollController, - physics: const AlwaysScrollableScrollPhysics(), - slivers: [ - // Header & Search - SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.all(16), - child: Container( - height: 40, - decoration: BoxDecoration( - color: AppColors.surface, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: AppColors.border), - ), - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - const Icon(Icons.search, size: 20, color: AppColors.textSecondary), - const SizedBox(width: 8), - Expanded( - child: TextField( - controller: _searchController, - style: const TextStyle(fontSize: 14, color: AppColors.textPrimary), - decoration: const InputDecoration( - hintText: 'Search Movies', - border: InputBorder.none, - isDense: true, - contentPadding: EdgeInsets.only(bottom: 11), - ), - onChanged: _onSearchChanged, - ), - ), - if (_isSearching) - const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2)), - if (_searchQuery.isNotEmpty) - GestureDetector( - onTap: () { - _searchController.clear(); - _onSearchChanged(''); - }, - child: const Icon(Icons.close, size: 16, color: AppColors.textSecondary), - ), - ], - ), - ), - ), - ), - - // Hero Section - if (_searchQuery.isEmpty && heroItems.isNotEmpty) - SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.only(bottom: 16), - child: SizedBox( - height: 250, - child: HeroCarousel( - items: heroItems, - onTap: (item) { - try { - final movie = _movies.firstWhere((element) => element.streamId == item.id); - _playMovie(movie); - } catch (e) { - // Fallback ignored - } - }, + return Container( + decoration: const BoxDecoration(gradient: AppColors.appleTvGradient), + child: SafeArea( + bottom: false, + child: RefreshIndicator( + onRefresh: _refresh, + color: AppColors.primary, + backgroundColor: AppColors.surface, + child: CustomScrollView( + controller: _scrollController, + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + // Header & Search + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.all(16), + child: GestureDetector( + onTap: () { + setState(() => _isSearchEditing = true); + WidgetsBinding.instance.addPostFrameCallback((_) { + _searchFocusNode.requestFocus(); + }); + }, + child: Container( + height: 40, + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: BorderRadius.circular(12), + border: _isSearchEditing + ? Border.all(color: AppColors.primary) + : Border.all(color: AppColors.border), + ), + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + const Icon(Icons.search, size: 20, color: AppColors.textSecondary), + const SizedBox(width: 8), + Expanded( + child: ExcludeFocus( + excluding: !_isSearchEditing, + child: TextField( + controller: _searchController, + focusNode: _searchFocusNode, + readOnly: !_isSearchEditing, + style: const TextStyle(fontSize: 14, color: AppColors.textPrimary), + decoration: const InputDecoration( + hintText: 'Search Movies', + border: InputBorder.none, + isDense: true, + contentPadding: EdgeInsets.only(bottom: 11), + ), + onChanged: _onSearchChanged, + onSubmitted: (_) => setState(() => _isSearchEditing = false), + ), + ), + ), + if (_isSearching) + const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2)), + if (_searchQuery.isNotEmpty) + GestureDetector( + onTap: () { + _searchController.clear(); + _onSearchChanged(''); + }, + child: const Icon(Icons.close, size: 16, color: AppColors.textSecondary), + ), + ], + ), ), - ), - ), - ), - - // Grid - SliverPadding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 80), - sliver: SliverGrid( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 8, - crossAxisSpacing: 8, - mainAxisSpacing: 8, - childAspectRatio: 0.7, - ), - delegate: SliverChildBuilderDelegate( - (context, index) { - if (index >= displayMovies.length) return null; - final movie = displayMovies[index]; - final isWatched = watchHistory.isMovieWatched(movie.streamId); - - return MediaCard( - title: movie.name, - imageUrl: _getImageUrl(movie.streamIcon), + ), + ), + ), - subtitle: movie.rating != null ? '${_formatRating(movie.rating)} ★' : null, - rating: _formatRating(movie.rating), - isWatched: isWatched, - onTap: () => _playMovie(movie), - onLongPress: () { - ref.read(mobileWatchHistoryProvider.notifier).toggleMovieWatched(movie.streamId); - }, - ); - }, - childCount: displayMovies.length, - ), - ), - ), - - if (_isLoading) - const SliverToBoxAdapter( - child: Padding( - padding: EdgeInsets.all(24), - child: Center(child: CircularProgressIndicator()), - ), - ), - ], - ), - ), - ); + // Hero Section + if (_searchQuery.isEmpty && heroItems.isNotEmpty) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.only(bottom: 16), + child: SizedBox( + height: 250, + child: HeroCarousel( + items: heroItems, + onTap: (item) { + try { + final movie = _movies.firstWhere((element) => element.streamId == item.id); + _playMovie(context, movie); + } catch (e) { + // Fallback ignored + } + }, + ), + ), + ), + ), + + // Grid + SliverPadding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 80), + sliver: SliverGrid( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 8, + crossAxisSpacing: 8, + mainAxisSpacing: 8, + childAspectRatio: 0.7, + ), + delegate: SliverChildBuilderDelegate( + (context, index) { + if (index >= displayMovies.length) return null; + final movie = displayMovies[index]; + final isWatched = watchHistory.isMovieWatched(movie.streamId); + + return TVFocusable( + onPressed: () => _playMovie(context, movie), + child: MediaCard( + title: movie.name, + imageUrl: _getImageUrl(movie.streamIcon), + subtitle: movie.rating != null ? '${_formatRating(movie.rating)} ★' : null, + rating: _formatRating(movie.rating), + isWatched: isWatched, + onTap: () => _playMovie(context, movie), + onLongPress: () { + ref.read(mobileWatchHistoryProvider.notifier).toggleMovieWatched(movie.streamId); + }, + ), + ); + }, + childCount: displayMovies.length, + ), + ), + ), + + if (_isLoading) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.all(24), + child: Center(child: CircularProgressIndicator()), + ), + ), + ], + ), + ), + ), + ); } } + diff --git a/lib/mobile/features/iptv/widgets/mobile_series_tab.dart b/lib/mobile/features/iptv/widgets/mobile_series_tab.dart index 75e5ade..a801025 100644 --- a/lib/mobile/features/iptv/widgets/mobile_series_tab.dart +++ b/lib/mobile/features/iptv/widgets/mobile_series_tab.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:xtremflow/mobile/widgets/tv_focusable.dart'; import '../../../../core/models/playlist_config.dart'; import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/components/hero_carousel.dart'; @@ -21,9 +23,11 @@ class MobileSeriesTab extends ConsumerStatefulWidget { class _MobileSeriesTabState extends ConsumerState with AutomaticKeepAliveClientMixin { final ScrollController _scrollController = ScrollController(); final TextEditingController _searchController = TextEditingController(); + final FocusNode _searchFocusNode = FocusNode(); final List _series = []; List? _searchResults; String _searchQuery = ''; + bool _isSearchEditing = false; bool _isLoading = false; bool _isSearching = false; bool _hasMore = true; @@ -42,6 +46,7 @@ class _MobileSeriesTabState extends ConsumerState with Automati void dispose() { _scrollController.dispose(); _searchController.dispose(); + _searchFocusNode.dispose(); _searchDebounce?.cancel(); super.dispose(); } @@ -197,7 +202,9 @@ class _MobileSeriesTabState extends ConsumerState with Automati onMoreInfo: () => _openSeries(s), )).toList(); - return SafeArea( + return Container( + decoration: const BoxDecoration(gradient: AppColors.appleTvGradient), + child: SafeArea( bottom: false, child: RefreshIndicator( onRefresh: _refresh, @@ -209,47 +216,63 @@ class _MobileSeriesTabState extends ConsumerState with Automati slivers: [ // Header & Search SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.all(16), - child: Container( - height: 40, - decoration: BoxDecoration( - color: AppColors.surface, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: AppColors.border), - ), - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - const Icon(Icons.search, size: 20, color: AppColors.textSecondary), - const SizedBox(width: 8), - Expanded( - child: TextField( - controller: _searchController, - style: const TextStyle(fontSize: 14, color: AppColors.textPrimary), - decoration: const InputDecoration( - hintText: 'Search Series', - border: InputBorder.none, - isDense: true, - contentPadding: EdgeInsets.only(bottom: 11), - ), - onChanged: _onSearchChanged, - ), + child: Padding( + padding: const EdgeInsets.all(16), + child: GestureDetector( + onTap: () { + setState(() => _isSearchEditing = true); + WidgetsBinding.instance.addPostFrameCallback((_) { + _searchFocusNode.requestFocus(); + }); + }, + child: Container( + height: 40, + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: BorderRadius.circular(12), + border: _isSearchEditing + ? Border.all(color: AppColors.primary) + : Border.all(color: AppColors.border), ), - if (_isSearching) - const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2)), - if (_searchQuery.isNotEmpty) - GestureDetector( - onTap: () { - _searchController.clear(); - _onSearchChanged(''); - }, - child: const Icon(Icons.close, size: 16, color: AppColors.textSecondary), - ), - ], + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + const Icon(Icons.search, size: 20, color: AppColors.textSecondary), + const SizedBox(width: 8), + Expanded( + child: ExcludeFocus( + excluding: !_isSearchEditing, + child: TextField( + controller: _searchController, + focusNode: _searchFocusNode, + readOnly: !_isSearchEditing, + style: const TextStyle(fontSize: 14, color: AppColors.textPrimary), + decoration: const InputDecoration( + hintText: 'Search Series', + border: InputBorder.none, + isDense: true, + contentPadding: EdgeInsets.only(bottom: 11), + ), + onChanged: _onSearchChanged, + onSubmitted: (_) => setState(() => _isSearchEditing = false), + ), + ), + ), + if (_isSearching) + const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2)), + if (_searchQuery.isNotEmpty) + GestureDetector( + onTap: () { + _searchController.clear(); + _onSearchChanged(''); + }, + child: const Icon(Icons.close, size: 16, color: AppColors.textSecondary), + ), + ], + ), + ), ), ), - ), ), // Hero Section @@ -293,14 +316,17 @@ class _MobileSeriesTabState extends ConsumerState with Automati if (index >= displaySeries.length) return null; final series = displaySeries[index]; - return MediaCard( - title: series.name, - imageUrl: _getImageUrl(series.cover), - - subtitle: series.rating != null ? '${_formatRating(series.rating)} ★' : null, - rating: _formatRating(series.rating), - placeholderIcon: Icons.tv, - onTap: () => _openSeries(series), + return TVFocusable( + onPressed: () => _openSeries(series), + child: MediaCard( + title: series.name, + imageUrl: _getImageUrl(series.cover), + + subtitle: series.rating != null ? '${_formatRating(series.rating)} ★' : null, + rating: _formatRating(series.rating), + placeholderIcon: Icons.tv, + onTap: () => _openSeries(series), + ), ); }, childCount: displaySeries.length, @@ -318,6 +344,7 @@ class _MobileSeriesTabState extends ConsumerState with Automati ], ), ), + ), ); } } diff --git a/lib/mobile/features/iptv/widgets/mobile_settings_tab.dart b/lib/mobile/features/iptv/widgets/mobile_settings_tab.dart index 899c767..68e59ce 100644 --- a/lib/mobile/features/iptv/widgets/mobile_settings_tab.dart +++ b/lib/mobile/features/iptv/widgets/mobile_settings_tab.dart @@ -5,6 +5,7 @@ import 'package:google_fonts/google_fonts.dart'; import '../../../providers/mobile_settings_providers.dart'; import '../../../../core/providers/theme_provider.dart'; import '../../../../core/theme/app_colors.dart'; +import '../screens/mobile_playlist_selection_screen.dart'; /// Simplified mobile settings tab - no auth, local storage only class MobileSettingsTab extends ConsumerStatefulWidget { @@ -167,6 +168,69 @@ class _MobileSettingsTabState extends ConsumerState { ), child: Column( children: [ + ListTile( + leading: const Icon(Icons.rocket_launch, color: AppColors.primary), + title: const Text('Moteur Vidéo', + style: TextStyle(color: AppColors.textPrimary)), + subtitle: Text( + settings.playerEngine == 'ultra' ? 'Ultra (MPV) - Puissant' : 'Lite (ExoPlayer) - Léger', + style: const TextStyle(color: AppColors.textSecondary), + ), + trailing: DropdownButton( + value: settings.playerEngine, + dropdownColor: AppColors.surface, + underline: const SizedBox(), + icon: const Icon(Icons.arrow_drop_down, color: AppColors.primary), + items: const [ + DropdownMenuItem(value: 'ultra', child: Text('Ultra', style: TextStyle(color: AppColors.textPrimary))), + DropdownMenuItem(value: 'lite', child: Text('Lite', style: TextStyle(color: AppColors.textPrimary))), + ], + onChanged: (val) { + if (val != null) { + ref.read(mobileSettingsProvider.notifier).setPlayerEngine(val); + } + }, + ), + ), + Divider(height: 1, color: AppColors.textSecondary.withOpacity(0.2)), + SwitchListTile( + title: const Text('Stats pour Nerds', + style: TextStyle(color: AppColors.textPrimary)), + subtitle: const Text('Infos techniques (FPS, Buffer)', + style: TextStyle(color: AppColors.textSecondary, fontSize: 12)), + secondary: const Icon(Icons.bug_report, color: AppColors.primary), + value: settings.showDebugStats, + onChanged: (val) => ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(val), + activeColor: AppColors.primary, + ), + Divider(height: 1, color: AppColors.textSecondary.withOpacity(0.2)), + ListTile( + leading: const Icon(Icons.memory, color: AppColors.primary), + title: const Text('Décodeur Vidéo', + style: TextStyle(color: AppColors.textPrimary)), + subtitle: Text( + settings.decoderMode == 'auto' ? 'Automatique (Recommandé)' : + settings.decoderMode == 'mediacodec' ? 'Matériel (Hardware)' : 'Logiciel (Software)', + style: const TextStyle(color: AppColors.textSecondary), + ), + trailing: DropdownButton( + value: settings.decoderMode, + dropdownColor: AppColors.surface, + underline: const SizedBox(), + icon: const Icon(Icons.arrow_drop_down, color: AppColors.primary), + items: const [ + DropdownMenuItem(value: 'auto', child: Text('Auto', style: TextStyle(color: AppColors.textPrimary))), + DropdownMenuItem(value: 'mediacodec', child: Text('Hardware', style: TextStyle(color: AppColors.textPrimary))), + DropdownMenuItem(value: 'no', child: Text('Software', style: TextStyle(color: AppColors.textPrimary))), + ], + onChanged: (val) { + if (val != null) { + ref.read(mobileSettingsProvider.notifier).setDecoderMode(val); + } + }, + ), + ), + Divider(height: 1, color: AppColors.textSecondary.withOpacity(0.2)), ListTile( leading: const Icon(Icons.speed, color: AppColors.primary), title: const Text('Mise en mémoire tampon (Cache)', @@ -259,8 +323,13 @@ class _MobileSettingsTabState extends ConsumerState { // Change Playlist InkWell( onTap: () { - // Navigate back to playlist selection - Navigator.of(context).popUntil((route) => route.isFirst); + // Open Playlist Selection in Manage Mode + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const MobilePlaylistSelectionScreen(manageMode: true), + ), + ); }, borderRadius: BorderRadius.circular(12), child: Container( @@ -274,7 +343,7 @@ class _MobileSettingsTabState extends ConsumerState { Icon(Icons.playlist_play, color: AppColors.textPrimary), SizedBox(width: 16), Text( - 'Changer de Playlist', + 'Gérer les Playlists', style: TextStyle( fontWeight: FontWeight.w600, color: AppColors.textPrimary, diff --git a/lib/mobile/providers/mobile_settings_providers.dart b/lib/mobile/providers/mobile_settings_providers.dart index f59678b..63cf059 100644 --- a/lib/mobile/providers/mobile_settings_providers.dart +++ b/lib/mobile/providers/mobile_settings_providers.dart @@ -9,6 +9,9 @@ class MobileSettings { final List moviesKeywords; final List seriesKeywords; final bool showClock; + final bool showDebugStats; + final String decoderMode; // 'auto', 'mediacodec' (HW), 'no' (SW) + final String playerEngine; // 'ultra' (MPV), 'lite' (ExoPlayer) final int bufferDuration; // seconds, 0 = auto const MobileSettings({ @@ -16,6 +19,9 @@ class MobileSettings { this.moviesKeywords = const [], this.seriesKeywords = const [], this.showClock = false, + this.showDebugStats = false, + this.decoderMode = 'auto', + this.playerEngine = 'ultra', this.bufferDuration = 0, }); @@ -24,6 +30,9 @@ class MobileSettings { List? moviesKeywords, List? seriesKeywords, bool? showClock, + bool? showDebugStats, + String? decoderMode, + String? playerEngine, int? bufferDuration, }) { return MobileSettings( @@ -31,6 +40,9 @@ class MobileSettings { moviesKeywords: moviesKeywords ?? this.moviesKeywords, seriesKeywords: seriesKeywords ?? this.seriesKeywords, showClock: showClock ?? this.showClock, + showDebugStats: showDebugStats ?? this.showDebugStats, + decoderMode: decoderMode ?? this.decoderMode, + playerEngine: playerEngine ?? this.playerEngine, bufferDuration: bufferDuration ?? this.bufferDuration, ); } @@ -78,6 +90,9 @@ class MobileSettingsNotifier extends StateNotifier { final movies = _box?.get('moviesKeywords', defaultValue: []) as List?; final series = _box?.get('seriesKeywords', defaultValue: []) as List?; final showClock = _box?.get('showClock', defaultValue: false) as bool?; + final showDebugStats = _box?.get('showDebugStats', defaultValue: false) as bool?; + final decoderMode = _box?.get('decoderMode', defaultValue: 'auto') as String?; + final playerEngine = _box?.get('playerEngine', defaultValue: 'ultra') as String?; final buffer = _box?.get('bufferDuration', defaultValue: 0) as int?; state = MobileSettings( @@ -85,6 +100,9 @@ class MobileSettingsNotifier extends StateNotifier { moviesKeywords: movies?.cast() ?? [], seriesKeywords: series?.cast() ?? [], showClock: showClock ?? false, + showDebugStats: showDebugStats ?? false, + decoderMode: decoderMode ?? 'auto', + playerEngine: playerEngine ?? 'ultra', bufferDuration: buffer ?? 0, ); } @@ -109,6 +127,21 @@ class MobileSettingsNotifier extends StateNotifier { _box?.put('showClock', value); } + void toggleShowDebugStats(bool value) { + state = state.copyWith(showDebugStats: value); + _box?.put('showDebugStats', value); + } + + void setDecoderMode(String mode) { + state = state.copyWith(decoderMode: mode); + _box?.put('decoderMode', mode); + } + + void setPlayerEngine(String engine) { + state = state.copyWith(playerEngine: engine); + _box?.put('playerEngine', engine); + } + void setBufferDuration(int seconds) { state = state.copyWith(bufferDuration: seconds); _box?.put('bufferDuration', seconds); diff --git a/lib/mobile/providers/mobile_xtream_providers.dart b/lib/mobile/providers/mobile_xtream_providers.dart index 78b2245..7cdacb4 100644 --- a/lib/mobile/providers/mobile_xtream_providers.dart +++ b/lib/mobile/providers/mobile_xtream_providers.dart @@ -63,3 +63,20 @@ final mobileSeriesInfoByPlaylistProvider = FutureProvider.family((ref) => LiveTvUiState()); + +class LiveTvUiState { + final String? selectedCategory; + final bool isCategoryView; + + LiveTvUiState({this.selectedCategory, this.isCategoryView = true}); + + LiveTvUiState copyWith({String? selectedCategory, bool? isCategoryView}) { + return LiveTvUiState( + selectedCategory: selectedCategory ?? this.selectedCategory, + isCategoryView: isCategoryView ?? this.isCategoryView, + ); + } +} diff --git a/lib/mobile/widgets/mobile_scaffold.dart b/lib/mobile/widgets/mobile_scaffold.dart index cd0a61c..3928340 100644 --- a/lib/mobile/widgets/mobile_scaffold.dart +++ b/lib/mobile/widgets/mobile_scaffold.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/theme/app_colors.dart'; +import 'tv_focusable.dart'; class MobileScaffold extends ConsumerWidget { final Widget child; @@ -17,39 +18,72 @@ class MobileScaffold extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( - extendBody: true, // Allow content behind nav bar if transparent backgroundColor: AppColors.background, - body: child, - bottomNavigationBar: Container( + body: Column( + children: [ + // Top Navigation Bar (TV Friendly) + Container( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + decoration: BoxDecoration( + color: AppColors.surface, + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.3), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: SafeArea( + bottom: false, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + _buildNavItem(0, 'Live TV', Icons.tv), + _buildNavItem(1, 'Films', Icons.movie), + _buildNavItem(2, 'Séries', Icons.video_library), + _buildNavItem(3, 'Paramètres', Icons.settings), + ], + ), + ), + ), + + // Main Content + Expanded(child: child), + ], + ), + ); + } + + Widget _buildNavItem(int index, String label, IconData icon) { + final isSelected = currentIndex == index; + return TVFocusable( + onPressed: () => onIndexChanged(index), + scale: 1.1, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( - border: Border(top: BorderSide(color: AppColors.border.withOpacity(0.5), width: 0.5)), + color: isSelected ? AppColors.primary.withOpacity(0.15) : null, + borderRadius: BorderRadius.circular(8), + border: isSelected ? Border.all(color: AppColors.primary.withOpacity(0.5)) : null, ), - child: BottomNavigationBar( - currentIndex: currentIndex, - onTap: onIndexChanged, - backgroundColor: AppColors.surface.withOpacity(0.95), // Highly opaque for readability - type: BottomNavigationBarType.fixed, - showSelectedLabels: true, - showUnselectedLabels: true, - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.tv), - label: 'Live', + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + color: isSelected ? AppColors.primary : AppColors.textSecondary, + size: 20, ), - BottomNavigationBarItem( - icon: Icon(Icons.movie_outlined), - activeIcon: Icon(Icons.movie), - label: 'Movies', - ), - BottomNavigationBarItem( - icon: Icon(Icons.video_library_outlined), - activeIcon: Icon(Icons.video_library), - label: 'Series', - ), - BottomNavigationBarItem( - icon: Icon(Icons.settings_outlined), - activeIcon: Icon(Icons.settings), - label: 'Settings', + const SizedBox(width: 8), + Text( + label, + style: TextStyle( + color: isSelected ? AppColors.primary : AppColors.textSecondary, + fontWeight: isSelected ? FontWeight.bold : FontWeight.w500, + fontSize: 14, + ), ), ], ), diff --git a/lib/mobile/widgets/tv_focusable.dart b/lib/mobile/widgets/tv_focusable.dart new file mode 100644 index 0000000..26e90de --- /dev/null +++ b/lib/mobile/widgets/tv_focusable.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import '../../../../core/theme/app_colors.dart'; + +class TVFocusable extends StatefulWidget { + final Widget child; + final VoidCallback? onPressed; + final VoidCallback? onFocus; + final FocusNode? focusNode; + final bool autofocus; + final double scale; + final double borderWidth; + final Color focusColor; + final BorderRadius? borderRadius; + + const TVFocusable({ + super.key, + required this.child, + this.onPressed, + this.onFocus, + this.focusNode, + this.autofocus = false, + this.scale = 1.05, + this.borderWidth = 3.0, + this.focusColor = Colors.white, + this.borderRadius, + }); + + @override + State createState() => _TVFocusableState(); +} + +class _TVFocusableState extends State { + late FocusNode _node; + bool _isFocused = false; + + @override + void initState() { + super.initState(); + _node = widget.focusNode ?? FocusNode(); + _node.addListener(_onFocusChanged); + } + + @override + void dispose() { + if (widget.focusNode == null) { + _node.dispose(); + } else { + _node.removeListener(_onFocusChanged); + } + super.dispose(); + } + + void _onFocusChanged() { + if (_node.hasFocus != _isFocused) { + setState(() => _isFocused = _node.hasFocus); + if (_isFocused) { + widget.onFocus?.call(); + _scrollToVisible(); + } + } + } + + void _scrollToVisible() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + Scrollable.ensureVisible( + context, + alignment: 0.5, // Center the item + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + }); + } + + void _handlePress() { + widget.onPressed?.call(); + } + + @override + Widget build(BuildContext context) { + return Focus( + focusNode: _node, + autofocus: widget.autofocus, + onKeyEvent: (node, event) { + if (event is KeyDownEvent) { + final key = event.logicalKey; + if (key == LogicalKeyboardKey.select || + key == LogicalKeyboardKey.enter || + key == LogicalKeyboardKey.space || + key == LogicalKeyboardKey.gameButtonA || + key == LogicalKeyboardKey.numpadEnter) { + _handlePress(); + return KeyEventResult.handled; + } + } + return KeyEventResult.ignored; + }, + child: GestureDetector( + onTap: _handlePress, + child: TweenAnimationBuilder( + duration: const Duration(milliseconds: 200), + curve: Curves.easeOut, + tween: Tween( + begin: 1.0, + end: _isFocused ? widget.scale : 1.0, + ), + builder: (context, scale, child) { + return Transform.scale( + scale: scale, + child: Container( + foregroundDecoration: _isFocused + ? BoxDecoration( + border: Border.all( + color: widget.focusColor, + width: widget.borderWidth, + ), + borderRadius: widget.borderRadius ?? BorderRadius.circular(12), + ) + : null, + child: child, + ), + ); + }, + child: widget.child, + ), + ), + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 0ca317a..f6d8221 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -46,6 +46,7 @@ dependencies: equatable: ^2.0.5 shared_preferences: ^2.3.2 path_provider: ^2.1.5 + video_player: ^2.10.1