Phase 3: Architecture refactor - consolidate folders and extract patterns

- Consolidate lib/mobile/features/iptv → lib/features/iptv
  * Move all IPTV screens, models, services, widgets to unified location
  * Update imports in main.dart and affected files
  * Remove old mobile/features/iptv directory

- Create lib/core/patterns/ for reusable implementations
  * HiveServiceBase: Template for Hive-based persistent storage
  * VideoPlayerWrapper: Abstraction for video player selection
  * StreamResolverPattern: IPTV stream resolution and validation

- Router already simplified (no kIsWeb checks, Android-only)

All changes maintain Android-only architecture and improve maintainability.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
GitHub CopilotandClaude Haiku 4.5 committed 2026-03-25 22:21:49 +01:00
1 parent d0f0589d09
commit cb1788be8a
16 files changed
+361 -5

No files matched your search

@@ -0,0 +1,8 @@
/// Xtream API Data Models - Mobile Version
///
/// This is a minimal stub to support mobile imports.
/// Full models are in core/models/iptv_models.dart
library;
// Re-export from core for compatibility
export '../../../core/models/iptv_models.dart';
@@ -0,0 +1,719 @@
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:wakelock_plus/wakelock_plus.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/features/iptv/screens/native_player_screen.dart';
import 'package:xtremflow/features/iptv/models/xtream_models.dart' as xm;
import 'package:xtremflow/mobile/widgets/tv_focusable.dart';
class LitePlayerScreen extends ConsumerStatefulWidget {
final String streamId;
final String title;
final StreamType streamType;
final String? containerExtension;
final PlaylistConfig playlist;
final List<Channel>? 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<LitePlayerScreen> createState() => _LitePlayerScreenState();
}
class _LitePlayerScreenState extends ConsumerState<LitePlayerScreen>
with WidgetsBindingObserver {
VideoPlayerController? _controller;
XtreamServiceMobile? _xtreamService;
bool _isLoading = true;
String? _errorMessage;
late int _currentIndex;
bool _showControls = true;
bool _isPlaying = false;
// EPG & Clock
xm.ShortEPG? _epg;
Timer? _epgTimer;
String _currentTime = "";
Timer? _clockTimer;
// Progress & Buffering
Duration _position = Duration.zero;
Duration _duration = Duration.zero;
bool _isSeeking = false;
bool _isStabilizing = false;
Timer? _stabilizationTimer;
Timer? _controlsTimer;
int _loadId = 0;
// Focus
final FocusNode _playPauseFocusNode = FocusNode();
final FocusNode _prevFocusNode = FocusNode();
final FocusNode _nextFocusNode = FocusNode();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
HardwareKeyboard.instance.addHandler(_handleKeyEvent);
WakelockPlus.enable();
_currentIndex = widget.initialIndex;
_startClock();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
_initializePlayback();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (_controller == null) return;
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.inactive ||
state == AppLifecycleState.detached) {
_controller?.pause();
if (mounted) {
Navigator.of(context).pop();
}
}
}
void _startClock() {
_clockTimer?.cancel();
_updateTime();
_clockTimer = Timer.periodic(
const Duration(seconds: 1),
(_) => _updateTime(),
);
}
void _updateTime() {
final now = DateTime.now();
final timeStr =
"${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}";
if (mounted && _currentTime != timeStr) {
setState(() => _currentTime = timeStr);
}
}
Future<void> _initializePlayback() async {
try {
final dir = await getApplicationDocumentsDirectory();
_xtreamService = XtreamServiceMobile(dir.path);
await _xtreamService!.setPlaylistAsync(widget.playlist);
_loadStream();
if (widget.streamType == StreamType.live) {
_updateEPG();
_epgTimer = Timer.periodic(
const Duration(minutes: 5),
(_) => _updateEPG(),
);
}
} catch (e) {
if (mounted) setState(() => _errorMessage = "Initialization Error: $e");
}
}
Future<void> _updateEPG() async {
if (widget.streamType != StreamType.live || _xtreamService == null) return;
try {
final currentChannelId =
widget.channels?[_currentIndex].streamId ?? widget.streamId;
final epgData = await _xtreamService!.getShortEPG(currentChannelId);
if (mounted) setState(() => _epg = epgData);
} catch (_) {}
}
Future<void> _loadStream() async {
if (_xtreamService == null) return;
await _controller?.dispose();
_controller = null;
if (!mounted) return;
setState(() {
_isLoading = true;
_errorMessage = null;
_isStabilizing = true;
_loadId++;
});
final currentLoadId = _loadId;
try {
final currentStreamId =
widget.channels != null && widget.channels!.isNotEmpty
? widget.channels![_currentIndex].streamId
: widget.streamId;
if (widget.streamType == StreamType.live) _updateEPG();
final streamUrl = widget.streamType == StreamType.live
? _xtreamService!.getLiveStreamUrl(currentStreamId)
: (widget.streamType == StreamType.vod
? _xtreamService!.getVodStreamUrl(
currentStreamId,
widget.containerExtension ?? 'mp4',
)
: _xtreamService!.getSeriesStreamUrl(
currentStreamId,
widget.containerExtension ?? 'mp4',
));
final controller = VideoPlayerController.networkUrl(
Uri.parse(streamUrl),
httpHeaders: {'User-Agent': 'XtremFlow/1.0'},
);
_controller = controller;
await controller.initialize().timeout(const Duration(seconds: 15),
onTimeout: () {
throw Exception('Connection timed out');
});
if (!mounted) {
await controller.dispose();
return;
}
// Buffer Optimization: Pre-roll delay for TS streams
if (widget.streamType == StreamType.live) {
await Future.delayed(const Duration(milliseconds: 2000));
}
await controller.play();
setState(() {
_isPlaying = true;
_duration = controller.value.duration;
});
_resetControlsTimer();
controller.addListener(_videoListener);
} catch (e) {
if (mounted && currentLoadId == _loadId)
setState(() {
_isLoading = false;
_errorMessage = "Playback Error: $e";
});
}
}
void _videoListener() {
if (_controller == null || !mounted) return;
final value = _controller!.value;
if (value.isPlaying != _isPlaying)
setState(() => _isPlaying = value.isPlaying);
// Stabilization Masking: spinner stays until 1.5s of smooth play
// Fix: If playing, ignore isBuffering to prevent infinite spinner on some TS streams
// Force hide loader immediately when playing
if (value.isPlaying) {
if (_isLoading) setState(() => _isLoading = false);
if (_errorMessage != null) setState(() => _errorMessage = null);
if (_isStabilizing) _isStabilizing = false;
_stabilizationTimer?.cancel();
} else {
final shouldShow = value.isBuffering || _isStabilizing;
if (shouldShow != _isLoading) setState(() => _isLoading = shouldShow);
}
if (!_isSeeking) {
setState(() {
_position = value.position;
_duration = value.duration;
});
}
if (value.hasError) setState(() => _errorMessage = value.errorDescription);
}
void _onUserInteraction() {
if (!mounted) return;
final wasShowing = _showControls;
setState(() => _showControls = true);
_resetControlsTimer();
// Auto-focus the play/pause button when OSD appears to ensure OK key works instantly
if (!wasShowing) {
Future.delayed(const Duration(milliseconds: 100), () {
if (mounted && _showControls) {
_playPauseFocusNode.requestFocus();
}
});
}
}
void _resetControlsTimer() {
_controlsTimer?.cancel();
if (_showControls && _isPlaying) {
_controlsTimer = Timer(const Duration(seconds: 12), () {
if (mounted) setState(() => _showControls = false);
});
}
}
void _togglePlayPause() {
if (_controller == null) return;
_controller!.value.isPlaying ? _controller!.pause() : _controller!.play();
_onUserInteraction();
}
void _switchChannel(int index) {
if (widget.channels == null) return;
setState(() => _currentIndex = index);
_onUserInteraction(); // Ensure OSD shows up and timer resets on channel change
_loadStream();
}
bool _handleKeyEvent(KeyEvent event) {
if (event is! KeyDownEvent) return false;
final key = event.logicalKey;
if (key == LogicalKeyboardKey.channelUp) {
if (widget.channels != null)
_switchChannel((_currentIndex + 1) % widget.channels!.length);
return true;
}
if (key == LogicalKeyboardKey.channelDown) {
if (widget.channels != null)
_switchChannel(
(_currentIndex - 1 + widget.channels!.length) %
widget.channels!.length,
);
return true;
}
if (!_showControls) {
if (key == LogicalKeyboardKey.select ||
key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.arrowUp ||
key == LogicalKeyboardKey.arrowDown ||
key == LogicalKeyboardKey.arrowLeft ||
key == LogicalKeyboardKey.arrowRight) {
_onUserInteraction();
return true;
}
}
if (key == LogicalKeyboardKey.escape || key == LogicalKeyboardKey.goBack) {
if (_showControls) {
setState(() => _showControls = false);
return true;
}
Navigator.pop(context);
return true;
}
return false;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
HardwareKeyboard.instance.removeHandler(_handleKeyEvent);
WakelockPlus.disable();
_clockTimer?.cancel();
_epgTimer?.cancel();
_controlsTimer?.cancel();
_stabilizationTimer?.cancel();
_controller?.pause(); // Force stop audio immediately
_controller?.dispose();
_xtreamService?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final settings = ref.watch(mobileSettingsProvider);
final title = widget.channels != null
? widget.channels![_currentIndex].name
: widget.title;
return Scaffold(
backgroundColor: Colors.black,
body: GestureDetector(
onTap: _onUserInteraction,
child: Stack(
children: [
// Video Surface
Center(
child: _controller != null && _controller!.value.isInitialized
? _buildAspectRatioWrapper()
: const CircularProgressIndicator(color: AppColors.primary),
),
// Top Bar (Back Button + Clock)
if (_showControls)
Positioned(
top: 0,
left: 0,
right: 0,
child: SafeArea(
child: Container(
padding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Back Button
TVFocusable(
onPressed: () => Navigator.pop(context),
borderRadius: BorderRadius.circular(50),
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black45,
shape: BoxShape.circle,
),
child: const Icon(
Icons.arrow_back,
color: Colors.white,
size: 28,
),
),
),
// Clock
if (settings.showClock)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.black45,
borderRadius: BorderRadius.circular(20),
),
child: Text(
_currentTime,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
),
),
// Error Overlay
if (_errorMessage != null)
Center(
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.black87,
borderRadius: BorderRadius.circular(8),
),
child: Text(
_errorMessage!,
style: const TextStyle(color: Colors.red),
),
),
),
// Loading Spinner
if (_isLoading)
const Center(
child: CircularProgressIndicator(color: AppColors.primary),
),
// OSD (EPG + Controls)
if (_showControls) _buildOSD(title),
],
),
),
);
}
Widget _buildAspectRatioWrapper() {
final mode = ref.read(mobileSettingsProvider).aspectRatioMode;
if (mode == 'fill')
return SizedBox.expand(child: VideoPlayer(_controller!));
if (mode == 'cover')
return SizedBox.expand(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.size.width,
height: _controller!.value.size.height,
child: VideoPlayer(_controller!),
),
),
);
return AspectRatio(
aspectRatio: _controller!.value.aspectRatio,
child: VideoPlayer(_controller!),
);
}
Widget _buildOSD(String title) {
return Positioned(
bottom: 20,
left: 20,
right: 20,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Seeker (VOD)
if (widget.streamType != StreamType.live) _buildSeeker(),
// Unified Box: EPG & Controls
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.7),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white10),
),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// EPG Info (Left)
Expanded(child: _buildEPGBox(title)),
const SizedBox(width: 24),
// Controls Continuity (Right)
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (widget.streamType == StreamType.live)
TVFocusable(
focusNode: _prevFocusNode,
onPressed: () => _switchChannel(
(_currentIndex -
1 +
(widget.channels?.length ?? 0)) %
(widget.channels?.length ?? 1),
),
child: const Icon(
Icons.skip_previous,
color: Colors.white,
size: 36,
),
),
const SizedBox(width: 16),
TVFocusable(
focusNode: _playPauseFocusNode,
onPressed: _togglePlayPause,
child: Icon(
_isPlaying
? Icons.pause_circle_filled
: Icons.play_circle_filled,
color: Colors.white,
size: 56,
),
),
const SizedBox(width: 16),
if (widget.streamType == StreamType.live)
TVFocusable(
focusNode: _nextFocusNode,
onPressed: () => _switchChannel(
(_currentIndex + 1) %
(widget.channels?.length ?? 1),
),
child: const Icon(
Icons.skip_next,
color: Colors.white,
size: 36,
),
),
const SizedBox(width: 16),
const SizedBox(width: 16),
// Deinterlace Button (Switches to Native Player with forced Deinterlace)
TVFocusable(
onPressed: () {
// Save preference using streamId
final streamId =
widget.channels?[_currentIndex].streamId ??
widget.streamId;
ref
.read(mobileSettingsProvider.notifier)
.toggleChannelDeinterlace(streamId);
// Switch to NativePlayer with Deinterlace ON
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => NativePlayerScreen(
streamId: streamId,
title: widget.channels?[_currentIndex].name ??
widget.title,
playlist: widget.playlist,
streamType: widget.streamType,
channels: widget.channels,
initialIndex: _currentIndex,
forceDeinterlace: true,
),
),
);
},
child: const Icon(
Icons
.grid_on, // Icon representing interlaced grid/mesh
color: Colors.white,
size: 32,
),
),
],
),
],
),
),
),
],
),
);
}
Widget _buildEPGBox(String title) {
String program = widget.streamType == StreamType.live
? (_epg?.nowPlaying ?? "Pas d'infos EPG")
: title;
String next =
_epg?.nextPlaying != null ? "Suivant: ${_epg!.nextPlaying}" : "";
double progress = _epg?.progress ?? 0.0;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (widget.channels != null &&
widget.channels![_currentIndex].streamIcon.isNotEmpty)
Container(
margin: const EdgeInsets.only(right: 12),
width: 40,
height: 40,
child: CachedNetworkImage(
imageUrl: widget.channels![_currentIndex].streamIcon,
),
),
Expanded(
child: Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 8),
Text(
program,
style: const TextStyle(
color: AppColors.primary,
fontSize: 16,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (widget.streamType == StreamType.live &&
_epg?.nowPlaying != null) ...[
const SizedBox(height: 6),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: progress,
backgroundColor: Colors.white10,
color: AppColors.primary,
minHeight: 4,
),
),
const SizedBox(height: 6),
Text(
next,
style: const TextStyle(color: Colors.white54, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
);
}
Widget _buildSeeker() {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Actions(
actions: {
DirectionalFocusIntent: CallbackAction<DirectionalFocusIntent>(
onInvoke: (intent) {
if (intent.direction == TraversalDirection.up ||
intent.direction == TraversalDirection.down) {
FocusScope.of(context).focusInDirection(intent.direction);
return null;
}
return null;
},
),
},
child: Shortcuts(
shortcuts: {
LogicalKeySet(LogicalKeyboardKey.arrowUp):
const DirectionalFocusIntent(TraversalDirection.up),
LogicalKeySet(LogicalKeyboardKey.arrowDown):
const DirectionalFocusIntent(TraversalDirection.down),
},
child: Slider(
value: _position.inSeconds.toDouble().clamp(
0,
_duration.inSeconds.toDouble(),
),
min: 0,
max: _duration.inSeconds.toDouble(),
activeColor: AppColors.primary,
inactiveColor: Colors.white24,
onChanged: (v) => setState(() {
_position = Duration(seconds: v.toInt());
_isSeeking = true;
}),
onChangeEnd: (v) {
_controller?.seekTo(Duration(seconds: v.toInt()));
_isSeeking = false;
_onUserInteraction();
},
),
),
),
);
}
}
@@ -0,0 +1,61 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/models/playlist_config.dart';
import '../../../widgets/mobile_scaffold.dart';
import '../../../theme/mobile_theme.dart';
import '../widgets/mobile_live_tv_tab.dart';
import '../widgets/mobile_movies_tab.dart';
import '../widgets/mobile_series_tab.dart';
import '../widgets/mobile_settings_tab.dart';
import '../../../providers/mobile_xtream_providers.dart';
class MobileDashboardScreen extends ConsumerStatefulWidget {
final PlaylistConfig playlist;
const MobileDashboardScreen({
super.key,
required this.playlist,
});
@override
ConsumerState<MobileDashboardScreen> createState() =>
_MobileDashboardScreenState();
}
class _MobileDashboardScreenState extends ConsumerState<MobileDashboardScreen> {
@override
Widget build(BuildContext context) {
final currentIndex = ref.watch(mobileDashboardIndexProvider);
// Determine which tab to show
Widget currentTab;
switch (currentIndex) {
case 0:
currentTab = MobileLiveTVTab(playlist: widget.playlist);
break;
case 1:
currentTab = MobileMoviesTab(playlist: widget.playlist);
break;
case 2:
currentTab = MobileSeriesTab(playlist: widget.playlist);
break;
case 3:
currentTab = const MobileSettingsTab();
break;
default:
currentTab = MobileLiveTVTab(playlist: widget.playlist);
}
return Theme(
data: MobileTheme.darkTheme,
child: MobileScaffold(
currentIndex: currentIndex,
onIndexChanged: (index) {
ref.read(mobileDashboardIndexProvider.notifier).state = index;
},
child: currentTab,
),
);
}
}
@@ -0,0 +1,761 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/models/playlist_config.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../theme/mobile_theme.dart';
import '../../../../core/services/playlist_api_service.dart';
import 'mobile_dashboard_screen.dart';
/// Provider for local playlists
final localPlaylistsProvider =
FutureProvider<List<PlaylistConfig>>((ref) async {
final service = PlaylistApiService();
return service.getPlaylists();
});
/// Mobile playlist selection screen - simplified without auth
class MobilePlaylistScreen extends ConsumerStatefulWidget {
const MobilePlaylistScreen({super.key});
@override
ConsumerState<MobilePlaylistScreen> createState() =>
_MobilePlaylistScreenState();
}
class _MobilePlaylistScreenState extends ConsumerState<MobilePlaylistScreen> {
final PlaylistApiService _playlistService = PlaylistApiService();
@override
void initState() {
super.initState();
// _playlistService.init(); // PlaylistAPI service inits internally via HiveService
// Auto-login: if playlists exist, navigate to first one automatically
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkAutoLogin();
});
}
Future<void> _checkAutoLogin() async {
try {
final playlists = await _playlistService.getPlaylists();
if (playlists.length == 1 && mounted) {
// Navigate to first playlist automatically
_navigateToDashboard(playlists.first);
}
} catch (e) {
debugPrint('Auto-login check failed: $e');
}
}
void _refreshPlaylists() {
ref.invalidate(localPlaylistsProvider);
}
void _navigateToDashboard(PlaylistConfig playlist) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MobileDashboardScreen(playlist: playlist),
),
);
}
void _showPlaylistDialog({PlaylistConfig? playlist}) {
final isEditing = playlist != null;
final nameController = TextEditingController(text: playlist?.name ?? '');
final dnsController = TextEditingController(text: playlist?.dns ?? '');
final usernameController =
TextEditingController(text: playlist?.username ?? '');
final passwordController =
TextEditingController(text: playlist?.password ?? '');
// Focus nodes for TV navigation
final nameFocus = FocusNode();
final dnsFocus = FocusNode();
final usernameFocus = FocusNode();
final passwordFocus = FocusNode();
final buttonFocus = FocusNode();
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => Container(
decoration: const BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(), // Ensure logical order
child: Padding(
padding: const EdgeInsets.all(24),
child: SingleChildScrollView(
// Ensure scrolling when keyboard/focus moves
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Handle bar
Center(
child: Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColors.textTertiary,
borderRadius: BorderRadius.circular(2),
),
),
),
const SizedBox(height: 24),
// Title
Text(
isEditing ? 'Modifier la playlist' : 'Ajouter une playlist',
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 24),
// Form fields
_buildTextField(
controller: nameController,
label: 'Nom',
hint: 'Ma Playlist IPTV',
icon: Icons.label_outline,
textAction: TextInputAction.next,
onSubmitted: () =>
FocusScope.of(context).requestFocus(dnsFocus),
focusNode: nameFocus,
nextFocus: dnsFocus,
),
const SizedBox(height: 16),
_buildTextField(
controller: dnsController,
label: 'Serveur URL',
hint: 'http://example.com:8080',
icon: Icons.dns_outlined,
keyboardType: TextInputType.url,
textAction: TextInputAction.next,
onSubmitted: () =>
FocusScope.of(context).requestFocus(usernameFocus),
focusNode: dnsFocus,
nextFocus: usernameFocus,
prevFocus: nameFocus,
),
const SizedBox(height: 16),
_buildTextField(
controller: usernameController,
label: 'Nom d\'utilisateur',
hint: 'username',
icon: Icons.person_outline,
textAction: TextInputAction.next,
onSubmitted: () =>
FocusScope.of(context).requestFocus(passwordFocus),
focusNode: usernameFocus,
nextFocus: passwordFocus,
prevFocus: dnsFocus,
),
const SizedBox(height: 16),
_buildTextField(
controller: passwordController,
label: 'Mot de passe',
hint: '••••••••',
icon: Icons.lock_outline,
obscureText: true,
textAction: TextInputAction.done,
onSubmitted: () =>
FocusScope.of(context).requestFocus(buttonFocus),
focusNode: passwordFocus,
nextFocus: buttonFocus,
prevFocus: usernameFocus,
),
const SizedBox(height: 32),
// Save button
SizedBox(
width: double.infinity,
child: FilledButton.icon(
focusNode: buttonFocus,
onPressed: () async {
if (nameController.text.isEmpty ||
dnsController.text.isEmpty ||
usernameController.text.isEmpty ||
passwordController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Veuillez remplir tous les champs'),
backgroundColor: AppColors.error,
),
);
return;
}
// Auto-fix URL scheme
String dns = dnsController.text.trim();
if (!dns.startsWith('http://') &&
!dns.startsWith('https://')) {
dns = 'http://$dns';
}
if (isEditing) {
await _playlistService.updatePlaylist(
id: playlist.id,
name: nameController.text.trim(),
dns: dns,
username: usernameController.text.trim(),
password: passwordController.text.trim(),
);
} else {
await _playlistService.createPlaylist(
name: nameController.text.trim(),
dns: dns,
username: usernameController.text.trim(),
password: passwordController.text.trim(),
);
}
if (mounted) {
Navigator.pop(context);
_refreshPlaylists();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
isEditing
? 'Playlist modifiée'
: 'Playlist ajoutée',
),
backgroundColor: Colors.green,
),
);
}
},
icon: Icon(isEditing ? Icons.save : Icons.add),
label: Text(isEditing ? 'Enregistrer' : 'Ajouter'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
const SizedBox(height: 16),
],
),
),
),
),
),
);
}
Widget _buildTextField({
required TextEditingController controller,
required String label,
required String hint,
required IconData icon,
bool obscureText = false,
TextInputType? keyboardType,
TextInputAction? textAction,
VoidCallback? onSubmitted,
FocusNode? focusNode, // This is now the "navigation" focus
FocusNode? nextFocus,
FocusNode? prevFocus,
}) {
// Create a dedicated internal focus node for the actual TextField
// We don't expose this, allowing us to control when the keyboard opens
// Since we are inside a stateless method but need state for focus nodes if we want to create them on the fly...
// Actually, to avoid State complexity, we will trust the passed 'focusNode' is for NAVIGATION.
// And we will use a LayoutBuilder + Stateful wrapper or just a customized Focus widget.
return _TVTextField(
controller: controller,
label: label,
hint: hint,
icon: icon,
obscureText: obscureText,
keyboardType: keyboardType,
textAction: textAction,
onSubmitted: onSubmitted,
navigationFocus: focusNode,
nextFocus: nextFocus,
prevFocus: prevFocus,
);
}
void _showOptionsSheet(PlaylistConfig playlist) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (context) => Container(
decoration: const BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 8),
Center(
child: Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColors.textTertiary,
borderRadius: BorderRadius.circular(2),
),
),
),
const SizedBox(height: 16),
ListTile(
leading: const Icon(Icons.edit, color: AppColors.textPrimary),
title: const Text(
'Modifier',
style: TextStyle(color: AppColors.textPrimary),
),
onTap: () {
Navigator.pop(context);
_showPlaylistDialog(playlist: playlist);
},
),
ListTile(
leading: const Icon(Icons.delete, color: AppColors.error),
title: const Text(
'Supprimer',
style: TextStyle(color: AppColors.error),
),
onTap: () {
Navigator.pop(context);
_showDeleteConfirmation(playlist);
},
),
const SizedBox(height: 16),
],
),
),
),
);
}
void _showDeleteConfirmation(PlaylistConfig playlist) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: AppColors.surface,
title: const Text(
'Supprimer la playlist ?',
style: TextStyle(color: AppColors.textPrimary),
),
content: Text(
'Voulez-vous supprimer "${playlist.name}" ?',
style: const TextStyle(color: AppColors.textSecondary),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Annuler'),
),
FilledButton(
onPressed: () async {
await _playlistService.deletePlaylist(playlist.id);
if (mounted) {
Navigator.pop(context);
_refreshPlaylists();
}
},
style: FilledButton.styleFrom(backgroundColor: AppColors.error),
child: const Text('Supprimer'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final playlistsAsync = ref.watch(localPlaylistsProvider);
return Theme(
data: MobileTheme.darkTheme,
child: Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: const Text('XtremFlow'),
centerTitle: true,
backgroundColor: AppColors.background,
elevation: 0,
),
body: playlistsAsync.when(
loading: () => const Center(
child: CircularProgressIndicator(color: AppColors.primary),
),
error: (error, stack) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: AppColors.error,
),
const SizedBox(height: 16),
const Text(
'Erreur de chargement',
style: TextStyle(color: AppColors.textPrimary),
),
const SizedBox(height: 8),
Text(
error.toString(),
style: const TextStyle(
color: AppColors.textSecondary,
fontSize: 12,
),
),
const SizedBox(height: 16),
TextButton.icon(
onPressed: _refreshPlaylists,
icon: const Icon(Icons.refresh),
label: const Text('Réessayer'),
),
],
),
),
data: (playlists) {
if (playlists.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(20),
),
child: const Icon(
Icons.playlist_add,
size: 40,
color: AppColors.textTertiary,
),
),
const SizedBox(height: 24),
const Text(
'Aucune playlist',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 8),
const Text(
'Ajoutez votre première playlist IPTV',
style: TextStyle(
color: AppColors.textSecondary,
),
),
const SizedBox(height: 32),
FilledButton.icon(
onPressed: () => _showPlaylistDialog(),
icon: const Icon(Icons.add),
label: const Text('Ajouter une playlist'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
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: 12),
itemBuilder: (context, index) {
final playlist = playlists[index];
return _PlaylistCard(
playlist: playlist,
onTap: () => _navigateToDashboard(playlist),
onLongPress: () => _showOptionsSheet(playlist),
);
},
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _showPlaylistDialog(),
backgroundColor: AppColors.primary,
child: const Icon(Icons.add),
),
),
);
}
}
class _PlaylistCard extends StatelessWidget {
final PlaylistConfig playlist;
final VoidCallback onTap;
final VoidCallback onLongPress;
const _PlaylistCard({
required this.playlist,
required this.onTap,
required this.onLongPress,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.border.withOpacity(0.3)),
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
onLongPress: onLongPress,
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Container(
width: 52,
height: 52,
decoration: BoxDecoration(
color: AppColors.primary.withOpacity(0.15),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.playlist_play,
color: AppColors.primary,
size: 28,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
playlist.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Text(
Uri.tryParse(playlist.dns)?.host ?? playlist.dns,
style: const TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
const Icon(
Icons.chevron_right,
color: AppColors.textTertiary,
),
IconButton(
icon: const Icon(
Icons.more_vert,
color: AppColors.textSecondary,
),
onPressed: onLongPress, // Re-use the options sheet logic
),
],
),
),
),
),
);
}
}
class _TVTextField extends StatefulWidget {
final TextEditingController controller;
final String label;
final String hint;
final IconData icon;
final bool obscureText;
final TextInputType? keyboardType;
final TextInputAction? textAction;
final VoidCallback? onSubmitted;
final FocusNode? navigationFocus;
final FocusNode? nextFocus;
final FocusNode? prevFocus;
const _TVTextField({
required this.controller,
required this.label,
required this.hint,
required this.icon,
this.obscureText = false,
this.keyboardType,
this.textAction,
this.onSubmitted,
this.navigationFocus,
this.nextFocus,
this.prevFocus,
});
@override
State<_TVTextField> createState() => _TVTextFieldState();
}
class _TVTextFieldState extends State<_TVTextField> {
late FocusNode _inputFocus;
late FocusNode _navFocus;
bool _isEditing = false;
@override
void initState() {
super.initState();
_inputFocus = FocusNode();
_navFocus = widget.navigationFocus ?? FocusNode();
// When input loses focus (keyboard closed), return to nav focus
_inputFocus.addListener(() {
if (!_inputFocus.hasFocus && _isEditing) {
setState(() => _isEditing = false);
_navFocus.requestFocus();
}
});
}
@override
void dispose() {
_inputFocus.dispose();
if (widget.navigationFocus == null) _navFocus.dispose();
super.dispose();
}
void _activateInput() {
setState(() => _isEditing = true);
// Wait for the widget to rebuild with canRequestFocus: true
WidgetsBinding.instance.addPostFrameCallback((_) {
_inputFocus.requestFocus();
SystemChannels.textInput.invokeMethod('TextInput.show');
});
}
@override
Widget build(BuildContext context) {
return Focus(
focusNode: _navFocus,
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) {
_activateInput();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.arrowDown && widget.nextFocus != null) {
widget.nextFocus!.requestFocus();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.arrowUp && widget.prevFocus != null) {
widget.prevFocus!.requestFocus();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
child: Builder(
builder: (context) {
final isFocused = Focus.of(context).hasFocus;
return GestureDetector(
onTap: _activateInput,
child: Container(
decoration: BoxDecoration(
border: isFocused
? Border.all(color: AppColors.primary, width: 2)
: null,
borderRadius: BorderRadius.circular(4),
),
// Ignore standard focus traversal to child, only allow programatic focus
child: ExcludeFocus(
excluding: !_isEditing,
child: TextField(
controller: widget.controller,
focusNode: _inputFocus,
// Prevent keyboard if somehow focused while not editing
readOnly: !_isEditing,
showCursor: _isEditing,
obscureText: widget.obscureText,
keyboardType: widget.keyboardType,
textInputAction: widget.textAction,
onSubmitted: (_) {
setState(() => _isEditing = false);
// Give focus back to nav node first so we can move to next
_navFocus.requestFocus();
widget.onSubmitted?.call();
},
style: const TextStyle(color: AppColors.textPrimary),
decoration: InputDecoration(
labelText: widget.label,
hintText: widget.hint,
prefixIcon: Icon(
widget.icon,
color: isFocused
? AppColors.primary
: AppColors.textSecondary,
),
labelStyle: TextStyle(
color: isFocused
? AppColors.primary
: AppColors.textSecondary,
),
hintStyle: const TextStyle(color: AppColors.textTertiary),
filled: true,
fillColor: AppColors.surface,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 14,
),
),
),
),
),
);
},
),
);
}
}
@@ -0,0 +1,415 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../../../core/services/playlist_api_service.dart';
import '../../../../core/models/playlist_config.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../theme/mobile_theme.dart';
final playlistsProvider = FutureProvider<List<PlaylistConfig>>((ref) async {
final service = PlaylistApiService();
return service.getPlaylists();
});
class MobilePlaylistSelectionScreen extends ConsumerStatefulWidget {
final bool manageMode;
const MobilePlaylistSelectionScreen({super.key, this.manageMode = false});
@override
ConsumerState<MobilePlaylistSelectionScreen> createState() =>
_MobilePlaylistSelectionScreenState();
}
class _MobilePlaylistSelectionScreenState
extends ConsumerState<MobilePlaylistSelectionScreen> {
@override
void initState() {
super.initState();
if (!widget.manageMode) {
// Check for auto-login after build
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkAutoLogin();
});
}
}
Future<void> _checkAutoLogin() async {
final playlists = await ref.read(playlistsProvider.future);
// Only auto-login if there is exactly ONE playlist
if (playlists.length == 1 && mounted) {
context.go('/dashboard', extra: playlists.first);
}
}
Future<void> _showPlaylistDialog({PlaylistConfig? playlist}) async {
final isEditing = playlist != null;
final nameController = TextEditingController(text: playlist?.name ?? '');
final dnsController = TextEditingController(text: playlist?.dns ?? '');
final userController =
TextEditingController(text: playlist?.username ?? '');
final passController =
TextEditingController(text: playlist?.password ?? '');
await showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: AppColors.surface,
title: Text(
isEditing ? 'Modifier la Playlist' : 'Ajouter une Playlist',
style: GoogleFonts.inter(color: Colors.white),
),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: nameController,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
labelText: 'Nom',
labelStyle: TextStyle(color: Colors.white70),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white24),
),
),
),
const SizedBox(height: 8),
TextField(
controller: dnsController,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
labelText: 'URL (DNS)',
labelStyle: TextStyle(color: Colors.white70),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white24),
),
),
),
const SizedBox(height: 8),
TextField(
controller: userController,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
labelText: 'Utilisateur',
labelStyle: TextStyle(color: Colors.white70),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white24),
),
),
),
const SizedBox(height: 8),
TextField(
controller: passController,
obscureText: true,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
labelText: 'Mot de passe',
labelStyle: TextStyle(color: Colors.white70),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white24),
),
),
),
],
),
),
actions: [
if (isEditing)
TextButton(
onPressed: () async {
final confirm = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: AppColors.surface,
title: const Text(
'Confirmer',
style: TextStyle(color: Colors.white),
),
content: const Text(
'Supprimer cette playlist ?',
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('Annuler'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style:
TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('Supprimer'),
),
],
),
);
if (confirm == true) {
await PlaylistApiService().deletePlaylist(playlist.id);
if (context.mounted) {
Navigator.pop(context);
ref.invalidate(playlistsProvider);
}
}
},
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('Supprimer'),
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Annuler'),
),
ElevatedButton(
onPressed: () async {
if (nameController.text.isEmpty || dnsController.text.isEmpty) {
return;
}
final service = PlaylistApiService();
if (isEditing) {
await service.updatePlaylist(
id: playlist.id,
name: nameController.text,
dns: dnsController.text,
username: userController.text,
password: passController.text,
);
} else {
await service.createPlaylist(
name: nameController.text,
dns: dnsController.text,
username: userController.text,
password: passController.text,
);
}
if (context.mounted) {
Navigator.pop(context);
ref.invalidate(playlistsProvider);
}
},
child: const Text('Enregistrer'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final playlistsAsync = ref.watch(playlistsProvider);
return Theme(
data: MobileTheme.darkTheme,
child: Scaffold(
extendBodyBehindAppBar: true, // For gradient
appBar: AppBar(
title: Text(widget.manageMode ? 'Gérer les Playlists' : 'Playlists'),
backgroundColor: Colors.transparent,
elevation: 0,
actions: [
if (widget.manageMode) ...[
IconButton(
icon: const Icon(Icons.add),
onPressed: () => _showPlaylistDialog(),
tooltip: 'Ajouter une playlist',
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
],
],
),
body: Container(
decoration: const BoxDecoration(
gradient: AppColors.appleTvGradient,
),
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.invalidate(playlistsProvider),
child: const Text('Réessayer'),
),
],
),
),
data: (playlists) {
if (playlists.isEmpty) {
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: () => _showPlaylistDialog(),
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.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,
manageMode: widget.manageMode,
onTap: () {
if (widget.manageMode) {
_showPlaylistDialog(playlist: playlist);
} else {
context.go('/dashboard', extra: playlist);
}
},
);
},
);
},
),
),
),
);
}
}
class _MobilePlaylistCard extends StatelessWidget {
final PlaylistConfig playlist;
final VoidCallback onTap;
final bool manageMode;
const _MobilePlaylistCard({
required this.playlist,
required this.onTap,
this.manageMode = false,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.border.withOpacity(0.5)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: AppColors.primary.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.playlist_play,
color: AppColors.primary,
size: 28,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
playlist.name,
style: GoogleFonts.inter(
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Text(
Uri.tryParse(playlist.dns)?.host ?? playlist.dns,
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.textSecondary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
if (manageMode)
const Icon(Icons.edit, color: AppColors.primary)
else
const Icon(
Icons.chevron_right,
color: AppColors.textTertiary,
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,424 @@
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 '../../../providers/mobile_xtream_providers.dart';
import '../../../providers/mobile_settings_providers.dart';
import 'native_player_screen.dart';
import '../../../../core/theme/app_colors.dart';
class MobileSeriesDetailScreen extends ConsumerStatefulWidget {
final Series series;
final PlaylistConfig playlist;
const MobileSeriesDetailScreen({
super.key,
required this.series,
required this.playlist,
});
@override
ConsumerState<MobileSeriesDetailScreen> createState() =>
_MobileSeriesDetailScreenState();
}
class _MobileSeriesDetailScreenState
extends ConsumerState<MobileSeriesDetailScreen> {
SeriesInfo? _seriesInfo;
bool _isLoading = true;
String? _error;
int _selectedSeason = 1;
@override
void initState() {
super.initState();
_loadSeriesInfo();
}
String? _formatRating(String? rating) {
if (rating == null || rating.isEmpty) return null;
final value = double.tryParse(rating);
if (value != null) {
return value.toStringAsFixed(1);
}
return rating;
}
Future<void> _loadSeriesInfo() async {
try {
setState(() {
_isLoading = true;
_error = null;
});
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
final info =
await service.getSeriesInfo(widget.series.seriesId.toString());
if (mounted) {
setState(() {
_seriesInfo = info;
_isLoading = false;
if (info.episodes.isNotEmpty) {
_selectedSeason = info.episodes.keys.first;
}
});
}
} catch (e) {
if (mounted) {
setState(() {
_error = e.toString();
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _error != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: AppColors.error,
),
const SizedBox(height: 16),
Text(
'Error: $_error',
style: const TextStyle(color: AppColors.textSecondary),
),
TextButton(
onPressed: _loadSeriesInfo,
child: const Text('Retry'),
),
],
),
)
: _buildMobileContent(),
);
}
Widget _buildMobileContent() {
if (_seriesInfo == null) return const SizedBox.shrink();
final currentEpisodes = _seriesInfo!.episodes[_selectedSeason] ?? [];
return CustomScrollView(
slivers: [
// App Bar with Cover
SliverAppBar(
expandedHeight: 280, // Reduced from 400 for better TV visibility
pinned: true,
backgroundColor: AppColors.background,
leading: Container(
margin: const EdgeInsets.all(8),
decoration: const BoxDecoration(
color: Colors.black45,
shape: BoxShape.circle,
),
child: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.pop(context),
tooltip: 'Back',
),
),
flexibleSpace: FlexibleSpaceBar(
background: Stack(
fit: StackFit.expand,
children: [
if (_seriesInfo!.cover != null)
CachedNetworkImage(
imageUrl: _seriesInfo!.cover!,
fit: BoxFit.cover,
errorWidget: (_, __, ___) =>
Container(color: Colors.grey.shade900),
),
// Gradient Overlay
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
AppColors.background.withOpacity(0.8),
AppColors.background,
],
stops: const [0.5, 0.8, 1.0],
),
),
),
// Info Overlay
Positioned(
bottom: 16,
left: 16,
right: 16,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
_seriesInfo!.name,
style: GoogleFonts.inter(
fontSize: 24,
fontWeight: FontWeight.bold,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 8),
Row(
children: [
if (_seriesInfo!.rating != null) ...[
const Icon(
Icons.star,
size: 16,
color: Colors.amber,
),
const SizedBox(width: 4),
Text(
_formatRating(_seriesInfo!.rating!)!,
style: const TextStyle(
color: AppColors.textSecondary,
fontSize: 13,
),
),
const SizedBox(width: 16),
],
Text(
'${_seriesInfo!.episodes.keys.length} Saisons',
style: const TextStyle(
color: AppColors.textSecondary,
fontSize: 13,
),
),
],
),
],
),
),
],
),
),
),
// Plot
if (_seriesInfo!.plot != null && _seriesInfo!.plot!.isNotEmpty)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
_seriesInfo!.plot!,
style: const TextStyle(
color: AppColors.textSecondary,
height: 1.4,
),
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
),
),
// Seasons Filter
SliverToBoxAdapter(
child: SizedBox(
height: 50,
child: Builder(
builder: (context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 16),
scrollDirection: Axis.horizontal,
itemCount: _seriesInfo!.episodes.keys.length,
separatorBuilder: (_, __) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final seasonNum =
_seriesInfo!.episodes.keys.elementAt(index);
final isSelected = seasonNum == _selectedSeason;
return ChoiceChip(
label: Text('Saison $seasonNum'),
selected: isSelected,
onSelected: (selected) {
if (selected) {
setState(() => _selectedSeason = seasonNum);
}
},
backgroundColor: isDark
? const Color(0xFF1C1C1E)
: Colors.grey.shade300,
selectedColor: isDark ? Colors.white : Colors.blue,
labelStyle: TextStyle(
color: isSelected
? (isDark ? Colors.black : Colors.white)
: (isDark
? Colors.grey.shade400
: Colors.grey.shade700),
fontWeight:
isSelected ? FontWeight.w600 : FontWeight.w400,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
showCheckmark: false,
side: BorderSide.none,
);
},
);
},
),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 16)),
// Episodes List
SliverPadding(
padding: const EdgeInsets.only(bottom: 32),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final episode = currentEpisodes[index];
return _buildEpisodeTile(episode);
},
childCount: currentEpisodes.length,
),
),
),
],
);
}
Widget _buildEpisodeTile(Episode episode) {
final watchHistory = ref.watch(mobileWatchHistoryProvider);
final episodeKey = MobileWatchHistory.episodeKey(
widget.series.seriesId,
_selectedSeason,
episode.episodeNum,
);
final isWatched = watchHistory.isEpisodeWatched(episodeKey);
final resumePos = watchHistory.getResumePosition(episodeKey);
// Calculate progress
double progress = 0.0;
if (episode.durationSecs != null &&
episode.durationSecs! > 0 &&
resumePos > 0) {
progress = (resumePos / episode.durationSecs!).clamp(0.0, 1.0);
}
// Force dark mode colors since background is hardcoded dark
const textColor = Colors.white;
final secondaryTextColor = Colors.grey.shade400;
const surfaceColor = Color(0xFF1C1C1E);
const primaryColor = Colors.white; // Or accent color if preferred
return InkWell(
onTap: () {
// Enforce Native Player for Series (VOD)
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,
// Pass explicit initial position for resume
initialPosition:
resumePos > 0 ? Duration(seconds: resumePos) : null,
),
),
);
},
child: Column(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: const BoxDecoration(
border: Border(bottom: BorderSide(color: Colors.white10)),
),
child: Row(
children: [
// Play Button / Indicator
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: isWatched ? primaryColor : surfaceColor,
shape: BoxShape.circle,
border: isWatched
? null
: Border.all(color: primaryColor, width: 2),
),
child: Icon(
isWatched ? Icons.check : Icons.play_arrow,
color: isWatched
? Colors.black // Checkmark on white bg
: primaryColor, // Play icon
size: 20,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'E${episode.episodeNum} - ${episode.title}',
style: TextStyle(
color: isWatched ? secondaryTextColor : textColor,
fontWeight: FontWeight.w600,
fontSize: 14,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (episode.durationSecs != null &&
episode.durationSecs! > 0)
Text(
_formatDuration(episode.durationSecs!),
style: TextStyle(
color: secondaryTextColor,
fontSize: 12,
),
),
],
),
),
],
),
),
// Progress Bar (Red like YouTube/Netflix)
if (progress > 0 && !isWatched)
LinearProgressIndicator(
value: progress,
backgroundColor: Colors.transparent,
valueColor: const AlwaysStoppedAnimation<Color>(Colors.red),
minHeight: 2,
),
],
),
);
}
String _formatDuration(int seconds) {
final hours = seconds ~/ 3600;
final minutes = (seconds % 3600) ~/ 60;
if (hours > 0) return '${hours}h ${minutes}m';
return '${minutes}m';
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
/// Xtream Codes API Service - Mobile Version
///
/// Handles Xtream API communication for mobile platforms.
/// This is a minimal stub for import compatibility.
library;
import '../models/xtream_models.dart' as xm;
/// Xtream API Service for Mobile
///
/// Placeholder implementation for mobile video streaming.
class XtreamServiceMobile {
// Minimal stub implementation
}
@@ -0,0 +1,700 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:io';
import '../../../providers/mobile_xtream_providers.dart';
import '../../../providers/mobile_settings_providers.dart';
import '../screens/native_player_screen.dart';
import '../../../../core/models/iptv_models.dart';
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/features/iptv/screens/lite_player_screen.dart';
import 'package:flutter/services.dart';
import '../../../../core/services/ip_service.dart';
class MobileLiveTVTab extends ConsumerStatefulWidget {
final PlaylistConfig playlist;
const MobileLiveTVTab({super.key, required this.playlist});
@override
ConsumerState<MobileLiveTVTab> createState() => _MobileLiveTVTabState();
}
class _MobileLiveTVTabState extends ConsumerState<MobileLiveTVTab>
with AutomaticKeepAliveClientMixin {
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocusNode = FocusNode();
String _searchQuery = '';
bool _showFavoritesOnly = false;
bool _isSearchEditing = false;
bool _justReturnedFromPlayer =
false; // Flag to prevent PopScope interception after player
@override
void initState() {
super.initState();
_searchController.addListener(() {
setState(() {
_searchQuery = _searchController.text.toLowerCase();
});
});
// Trigger IP fetch for smart sorting
IpService().fetchIpDetails().then((_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
_searchController.dispose();
_searchFocusNode.dispose();
super.dispose();
}
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
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 Container(
decoration: const BoxDecoration(gradient: AppColors.appleTvGradient),
child: Scaffold(
backgroundColor: Colors.transparent,
body: PopScope(
// Only allow full pop if we're at category view with no filters AND not just returned from player
canPop: false,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
// If just returned from player, reset the flag and do nothing (stay on channel list)
if (_justReturnedFromPlayer) {
_justReturnedFromPlayer = false;
return;
}
if (_searchQuery.isNotEmpty) {
setState(() {
_searchController.clear();
_searchQuery = '';
});
} else if (_showFavoritesOnly) {
setState(() => _showFavoritesOnly = false);
} else if (!uiState.isCategoryView) {
uiNotifier.state = uiState.copyWith(isCategoryView: true);
} else {
// Root View (Categories) -> Show Exit Dialog
final shouldExit = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.grey[900],
title: const Text(
"Quitter l'application",
style: TextStyle(color: Colors.white),
),
content: const Text(
"Voulez-vous vraiment quitter l'application ?",
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
autofocus: true,
child: const Text(
'Annuler',
style: TextStyle(color: Colors.blueAccent),
),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text(
'Quitter',
style: TextStyle(color: Colors.redAccent),
),
),
],
),
);
if (shouldExit == true) {
SystemNavigator.pop();
}
}
},
child: channelsAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, s) => Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Erreur: $e',
style: const TextStyle(color: Colors.red),
textAlign: TextAlign.center,
),
),
),
data: (groupedChannels) {
// Prepare categories
var categories = groupedChannels.keys.toList();
if (settings.liveTvKeywords.isNotEmpty) {
categories = categories
.where((cat) => settings.matchesLiveTvFilter(cat))
.toList();
categories.sort();
} else {
// Smart Sort (GeoIP)
final userCountry = IpService().country;
categories.sort((a, b) {
if (userCountry != null) {
final aMatches =
a.toLowerCase().contains(userCountry.toLowerCase());
final bMatches =
b.toLowerCase().contains(userCountry.toLowerCase());
if (aMatches && !bMatches) return -1;
if (!aMatches && bMatches) return 1;
}
return a.compareTo(b);
});
}
// Prepare channels
List<Channel> displayedChannels = [];
// Determine mode based on search/favorites/selection
bool showGrid = uiState.isCategoryView &&
_searchQuery.isEmpty &&
!_showFavoritesOnly;
if (!showGrid) {
if (_searchQuery.isNotEmpty) {
displayedChannels = groupedChannels.values
.expand((l) => l)
.where((c) => c.name.toLowerCase().contains(_searchQuery))
.toList();
} else if (_showFavoritesOnly) {
displayedChannels = groupedChannels.values
.expand((l) => l)
.where((c) => favorites.contains(c.streamId))
.toList();
} else if (uiState.selectedCategory != null) {
displayedChannels =
groupedChannels[uiState.selectedCategory] ?? [];
}
}
return SafeArea(
bottom: false,
child: Column(
children: [
// Header (Search + Title/Back)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: Column(
children: [
// Search Bar - Wrapped in TVFocusable for remote access
TVFocusable(
scale: 1.0, // Disable scaling to prevent overflow
focusColor:
Colors.white, // Solid white selection frame
onPressed: () {
setState(() => _isSearchEditing = true);
WidgetsBinding.instance.addPostFrameCallback((_) {
_searchFocusNode.requestFocus();
SystemChannels.textInput
.invokeMethod('TextInput.show');
});
},
borderRadius: BorderRadius.circular(12),
child: Container(
height: 48,
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(12),
// Removed internal editing border here to prevent conflict and "inside frame" look
),
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(
cursorColor:
Colors.white, // Extra safety
controller: _searchController,
focusNode: _searchFocusNode,
readOnly: !_isSearchEditing,
style: const TextStyle(
color: AppColors.textPrimary,
),
decoration: const InputDecoration(
hintText: 'Rechercher une chaîne...',
border: InputBorder.none,
focusedBorder: InputBorder
.none, // Explicitly remove focus border
enabledBorder: InputBorder.none,
isDense: true,
),
onSubmitted: (_) => setState(
() => _isSearchEditing = false,
),
),
),
),
if (_searchQuery.isNotEmpty)
GestureDetector(
onTap: () => _searchController.clear(),
child: const Icon(
Icons.close,
color: AppColors.textSecondary,
),
),
],
),
),
),
const SizedBox(height: 12),
// Title / Navigation Row
Row(
children: [
if (!showGrid ||
_showFavoritesOnly ||
_searchQuery.isNotEmpty) ...[
IconButton(
icon: const Icon(
Icons.arrow_back,
color: AppColors.textPrimary,
),
onPressed: () {
if (_searchQuery.isNotEmpty) {
_searchController.clear();
} else if (_showFavoritesOnly) {
setState(
() => _showFavoritesOnly = false,
);
} else {
uiNotifier.state = uiState.copyWith(
isCategoryView: true,
);
}
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
const SizedBox(width: 12),
],
Expanded(
child: Text(
_searchQuery.isNotEmpty
? 'Résultats de recherche'
: _showFavoritesOnly
? 'Favoris'
: showGrid
? 'Catégories'
: uiState.selectedCategory ??
'Chaînes',
style: const TextStyle(
color: AppColors.textPrimary,
fontWeight: FontWeight.bold,
fontSize: 18,
),
overflow: TextOverflow.ellipsis,
),
),
IconButton(
icon: Icon(
_showFavoritesOnly
? Icons.favorite
: Icons.favorite_border,
color: _showFavoritesOnly
? AppColors.error
: AppColors.textSecondary,
),
onPressed: () => setState(() {
_showFavoritesOnly = !_showFavoritesOnly;
// Reset category view if entering favorites
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) {
uiNotifier.state =
uiState.copyWith(isCategoryView: true);
}
}),
),
],
),
],
),
),
// Main Content
Expanded(
child: showGrid
? _buildCategoryGrid(categories)
: _buildChannelList(displayedChannels),
),
],
),
);
},
),
),
),
);
}
Widget _buildCategoryGrid(List<String> categories) {
if (categories.isEmpty) {
return Center(
child: Text(
'Aucune catégorie trouvée',
style: GoogleFonts.inter(color: AppColors.textSecondary),
),
);
}
return GridView.builder(
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 6, // Adjusted to 6 columns as requested
childAspectRatio: 1.0,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
itemCount: categories.length,
itemBuilder: (context, index) {
final category = categories[index];
return TVFocusable(
onPressed: () {
ref.read(mobileLiveTvUiStateProvider.notifier).state =
LiveTvUiState(
selectedCategory: category,
isCategoryView: false,
);
},
borderRadius: BorderRadius.circular(16),
child: Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xFF4A4A4C), // Lighter grey top
Color(0xFF2C2C2E), // Medium grey bottom
],
),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withOpacity(0.05)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 8,
offset: const Offset(0, 4),
),
],
),
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.tv,
color: AppColors.primary,
size: 32,
),
const SizedBox(height: 12),
Text(
category,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 14,
),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
),
);
},
);
}
Widget _buildChannelList(List<Channel> channels) {
if (channels.isEmpty) {
return Center(
child: Text(
'Aucune chaîne trouvée',
style: GoogleFonts.inter(color: AppColors.textSecondary),
),
);
}
return GridView.builder(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 80),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 6,
childAspectRatio: 0.85,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
itemCount: channels.length,
itemBuilder: (context, index) {
final channel = channels[index];
return _MobileChannelCard(
channel: channel,
playlist: widget.playlist,
onTap: () =>
_playChannel(context, channel, channels, widget.playlist, index),
);
},
);
}
void _playChannel(
BuildContext context,
Channel channel,
List<Channel> channels,
PlaylistConfig playlist,
int index,
) async {
final settings = ref.read(mobileSettingsProvider);
// Check if channel has forced deinterlacing enabled
final forceDeinterlace =
settings.deinterlacedChannels.contains(channel.streamId);
if (forceDeinterlace) {
await 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,
forceDeinterlace: true,
),
),
);
} else {
await 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,
),
),
);
}
// When returning from player, set flag to prevent PopScope from going back to categories
if (mounted) {
setState(() => _justReturnedFromPlayer = true);
}
}
}
class _MobileChannelCard extends ConsumerStatefulWidget {
final Channel channel;
final VoidCallback onTap;
final PlaylistConfig playlist;
const _MobileChannelCard({
required this.channel,
required this.onTap,
required this.playlist,
});
@override
ConsumerState<_MobileChannelCard> createState() => _MobileChannelCardState();
}
class _MobileChannelCardState extends ConsumerState<_MobileChannelCard> {
String? _epgTitle;
@override
void initState() {
super.initState();
_loadEpg();
}
Future<void> _loadEpg() async {
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
final epg = await service.getShortEPG(widget.channel.streamId);
if (mounted && epg.nowPlaying != null && epg.nowPlaying!.isNotEmpty) {
setState(() {
_epgTitle = epg.nowPlaying;
});
}
} catch (e) {
// Ignore EPG errors
}
}
@override
Widget build(BuildContext context) {
final iconUrl = widget.channel.streamIcon.isNotEmpty &&
widget.channel.streamIcon.startsWith('http')
? widget.channel.streamIcon
: null;
final favorites = ref.watch(mobileFavoritesProvider);
final isFavorite = favorites.contains(widget.channel.streamId);
return TVFocusable(
onPressed: widget.onTap,
onLongPress: () {
ref
.read(mobileFavoritesProvider.notifier)
.toggle(widget.channel.streamId);
},
child: Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xFF4A4A4C), // Lighter grey top
Color(0xFF2C2C2E), // Medium grey bottom
],
),
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Channel Logo
Expanded(
flex: 3,
child: Container(
width: double.infinity,
decoration: const BoxDecoration(
color: Colors.black26,
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
child: Stack(
children: [
// Logo
Center(
child: iconUrl != null
? CachedNetworkImage(
imageUrl: iconUrl,
fit: BoxFit.contain,
errorWidget: (_, __, ___) => const Icon(
Icons.tv,
color: Colors.white38,
size: 40,
),
placeholder: (_, __) => const Icon(
Icons.tv,
color: Colors.white24,
size: 40,
),
)
: const Icon(
Icons.tv,
color: Colors.white38,
size: 40,
),
),
// Favorite badge
if (isFavorite)
Positioned(
top: 4,
right: 4,
child: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.favorite,
color: Colors.white,
size: 12,
),
),
),
],
),
),
),
// Channel Name
Expanded(
flex: 2,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
widget.channel.name,
style: const TextStyle(
color: AppColors.textPrimary,
fontWeight: FontWeight.w500,
fontSize: 11,
),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (_epgTitle != null) ...[
const SizedBox(height: 2),
Text(
_epgTitle!,
style: const TextStyle(
color: Colors.yellow,
fontSize: 9,
),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
),
),
],
),
),
);
}
}
@@ -0,0 +1,522 @@
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 'package:xtremflow/mobile/widgets/mobile_poster_card.dart';
import '../../../../core/models/playlist_config.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../providers/mobile_settings_providers.dart';
import '../../../providers/mobile_xtream_providers.dart';
import '../screens/native_player_screen.dart';
class MobileMoviesTab extends ConsumerStatefulWidget {
final PlaylistConfig playlist;
const MobileMoviesTab({super.key, required this.playlist});
@override
ConsumerState<MobileMoviesTab> createState() => _MobileMoviesTabState();
}
class _MobileMoviesTabState extends ConsumerState<MobileMoviesTab>
with AutomaticKeepAliveClientMixin {
final ScrollController _scrollController = ScrollController();
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocusNode = FocusNode();
// Data
List<MapEntry<String, String>> _categories = [];
List<Movie> _categoryMovies = [];
String? _selectedCategoryId;
String? _selectedCategoryName;
// Search
List<Movie>? _searchResults;
String _searchQuery = '';
bool _isSearchEditing = false;
bool _isSearching = false;
Timer? _searchDebounce;
// State
bool _isLoading = false;
@override
void initState() {
super.initState();
// Defer initial load
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _categories.isEmpty) {
_loadCategories();
}
});
}
@override
void dispose() {
_scrollController.dispose();
_searchController.dispose();
_searchFocusNode.dispose();
_searchDebounce?.cancel();
super.dispose();
}
void _onSearchChanged(String query) {
_searchDebounce?.cancel();
setState(() {
_searchQuery = query;
if (query.isEmpty) {
_searchResults = null;
_isSearching = false;
}
});
if (query.length >= 2) {
_searchDebounce = Timer(const Duration(milliseconds: 500), () {
_performSearch(query);
});
}
}
Future<void> _performSearch(String query) async {
if (query.isEmpty) return;
setState(() => _isSearching = true);
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
final results = await service.searchMovies(query);
if (mounted && _searchQuery == query) {
setState(() {
_searchResults = results;
_isSearching = false;
});
}
} catch (e) {
if (mounted) setState(() => _isSearching = false);
}
}
Future<void> _loadCategories() async {
if (_isLoading || !mounted) return;
setState(() => _isLoading = true);
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
final categoriesMap = await service.getVodCategories();
if (mounted) {
setState(() {
_categories = categoriesMap.entries.toList()
..sort((a, b) => a.value.compareTo(b.value));
_isLoading = false;
});
}
} catch (e) {
if (mounted) setState(() => _isLoading = false);
}
}
Future<void> _selectCategory(String id, String name) async {
setState(() {
_selectedCategoryId = id;
_selectedCategoryName = name;
_categoryMovies = [];
_isLoading = true;
});
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
final movies = await service.getMoviesByCategory(id);
if (mounted) {
setState(() {
_categoryMovies = movies;
_isLoading = false;
});
}
} catch (e) {
if (mounted) setState(() => _isLoading = false);
}
}
void _onBack() {
if (_searchQuery.isNotEmpty) {
_onSearchChanged('');
_searchController.clear();
setState(() => _isSearchEditing = false);
return;
}
if (_selectedCategoryId != null) {
setState(() {
_selectedCategoryId = null;
_selectedCategoryName = null;
_categoryMovies = [];
});
return;
}
}
Future<void> _refresh() async {
// Clear service cache to force fresh data
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
service.clearCache();
} catch (_) {}
setState(() {
_categories.clear();
_selectedCategoryId = null;
_selectedCategoryName = null;
_categoryMovies.clear();
_searchResults = null;
_searchQuery = '';
_searchController.clear();
_isLoading = false;
});
await _loadCategories();
}
String? _formatRating(String? rating) {
if (rating == null || rating.isEmpty) return null;
final value = double.tryParse(rating);
if (value != null) {
return value.toStringAsFixed(1);
}
return rating;
}
/// On mobile, use direct URLs (no proxy needed)
String _getImageUrl(String? originalUrl) {
if (originalUrl == null || originalUrl.isEmpty) return '';
return originalUrl;
}
void _playMovie(BuildContext context, Movie movie) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NativePlayerScreen(
streamId: movie.streamId,
title: movie.name,
playlist: widget.playlist,
streamType: StreamType.vod,
containerExtension: movie.containerExtension,
),
),
);
}
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
final settings = ref.watch(mobileSettingsProvider);
final watchHistory = ref.watch(mobileWatchHistoryProvider);
// Initial load retry
if (_categories.isEmpty && !_isLoading) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _categories.isEmpty) {
_loadCategories();
}
});
}
// Determine what to display
final bool showingCategories =
_searchQuery.isEmpty && _selectedCategoryId == null;
final bool showingMovies =
_searchQuery.isEmpty && _selectedCategoryId != null;
final bool showingSearch = _searchQuery.isNotEmpty;
// Filter categories based on settings
final filteredCategories = _categories
.where((entry) => settings.matchesMoviesFilter(entry.value))
.toList();
int itemCount = 0;
if (showingCategories) {
itemCount = filteredCategories.length;
} else if (showingMovies) {
itemCount = _categoryMovies.length;
} else if (showingSearch) {
itemCount = _searchResults?.length ?? 0;
}
return Container(
decoration: const BoxDecoration(gradient: AppColors.appleTvGradient),
child: PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
// Handle Search Exit
if (_searchQuery.isNotEmpty || _isSearching) {
_onSearchChanged(''); // clear search
_searchController.clear();
setState(() => _isSearchEditing = false);
return;
}
// Handle Category Back
if (_selectedCategoryId != null) {
_onBack();
return;
}
// Root View -> Show Exit Dialog
final shouldExit = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.grey[900],
title: const Text(
"Quitter l'application",
style: TextStyle(color: Colors.white),
),
content: const Text(
"Voulez-vous vraiment quitter l'application ?",
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
autofocus: true,
child: const Text(
'Annuler',
style: TextStyle(color: Colors.blueAccent),
),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text(
'Quitter',
style: TextStyle(color: Colors.redAccent),
),
),
],
),
);
if (shouldExit == true) {
SystemNavigator.pop();
}
},
child: SafeArea(
bottom: false,
child: RefreshIndicator(
onRefresh: _refresh,
color: AppColors.primary,
backgroundColor: AppColors.surface,
child: CustomScrollView(
controller: _scrollController,
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
// Category Title (If inside a category)
if (showingMovies)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
children: [
IconButton(
icon: const Icon(
Icons.arrow_back,
color: Colors.white,
),
onPressed: _onBack,
),
const SizedBox(width: 8),
Expanded(
child: Text(
_selectedCategoryName ?? 'Films',
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
),
// Search Bar
SliverToBoxAdapter(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: TVFocusable(
scale: 1.0,
focusColor: Colors.white,
onPressed: () {
setState(() => _isSearchEditing = true);
WidgetsBinding.instance.addPostFrameCallback((_) {
_searchFocusNode.requestFocus();
});
},
borderRadius: BorderRadius.circular(12),
child: Container(
height: 40,
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(12),
),
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(
cursorColor: Colors.white,
controller: _searchController,
focusNode: _searchFocusNode,
readOnly: !_isSearchEditing,
style: const TextStyle(
fontSize: 14,
color: AppColors.textPrimary,
),
decoration: InputDecoration(
hintText: _selectedCategoryId != null
? 'Recherche Globale (Tout le catalogue)'
: 'Rechercher un film...',
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: 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: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: showingCategories
? 4
: 8, // Bigger cards for categories
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: showingCategories
? 2.5
: 0.7, // Wide cards for categories
),
delegate: SliverChildBuilderDelegate(
(context, index) {
if (showingCategories) {
if (index >= filteredCategories.length) return null;
final cat = filteredCategories[index];
return MobilePosterCard(
title: cat.value, // Name
imageUrl: null, // No image for category
placeholderIcon: Icons.folder, // Folder icon
onTap: () => _selectCategory(cat.key, cat.value),
isWatched: false,
);
} else if (showingMovies) {
if (index >= _categoryMovies.length) return null;
final movie = _categoryMovies[index];
final isWatched =
watchHistory.isMovieWatched(movie.streamId);
return MobilePosterCard(
title: movie.name,
imageUrl: _getImageUrl(movie.streamIcon),
rating: _formatRating(movie.rating),
isWatched: isWatched,
onTap: () => _playMovie(context, movie),
onLongPress: () {
ref
.read(mobileWatchHistoryProvider.notifier)
.toggleMovieWatched(movie.streamId);
},
);
} else if (showingSearch) {
if (_searchResults == null ||
index >= _searchResults!.length) {
return null;
}
final movie = _searchResults![index];
final isWatched =
watchHistory.isMovieWatched(movie.streamId);
return MobilePosterCard(
title: movie.name,
imageUrl: _getImageUrl(movie.streamIcon),
rating: _formatRating(movie.rating),
isWatched: isWatched,
onTap: () => _playMovie(context, movie),
onLongPress: () {
ref
.read(mobileWatchHistoryProvider.notifier)
.toggleMovieWatched(movie.streamId);
},
);
}
return null;
},
childCount: itemCount,
),
),
),
if (_isLoading)
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(24),
child: Center(child: CircularProgressIndicator()),
),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,433 @@
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 'package:xtremflow/mobile/widgets/mobile_poster_card.dart';
import '../../../../core/models/playlist_config.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/widgets/components/hero_carousel.dart';
import '../../../../core/widgets/components/ui_components.dart';
import '../../../providers/mobile_settings_providers.dart';
import '../../../providers/mobile_xtream_providers.dart';
import '../../../../features/iptv/services/xtream_service_mobile.dart';
import '../screens/mobile_series_detail_screen.dart';
class MobileSeriesTab extends ConsumerStatefulWidget {
final PlaylistConfig playlist;
const MobileSeriesTab({super.key, required this.playlist});
@override
ConsumerState<MobileSeriesTab> createState() => _MobileSeriesTabState();
}
class _MobileSeriesTabState extends ConsumerState<MobileSeriesTab>
with AutomaticKeepAliveClientMixin {
final ScrollController _scrollController = ScrollController();
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocusNode = FocusNode();
final List<Series> _series = [];
List<Series>? _searchResults;
String _searchQuery = '';
bool _isSearchEditing = false;
bool _isLoading = false;
bool _isSearching = false;
bool _hasMore = true;
int _currentOffset = 0;
static const int _pageSize = 50;
Timer? _searchDebounce;
@override
void initState() {
super.initState();
_loadMoreSeries();
_scrollController.addListener(_onScroll);
}
@override
void dispose() {
_scrollController.dispose();
_searchController.dispose();
_searchFocusNode.dispose();
_searchDebounce?.cancel();
super.dispose();
}
void _onScroll() {
// Only trigger load when near bottom and not already loading
if (!_isLoading &&
_hasMore &&
_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent * 0.8) {
_loadMoreSeries();
}
}
void _onSearchChanged(String query) {
_searchDebounce?.cancel();
setState(() {
_searchQuery = query;
if (query.isEmpty) {
_searchResults = null;
_isSearching = false;
}
});
if (query.length >= 2) {
_searchDebounce = Timer(const Duration(milliseconds: 500), () {
_performSearch(query);
});
}
}
Future<void> _performSearch(String query) async {
if (query.isEmpty) return;
setState(() => _isSearching = true);
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
final results = await service.searchSeries(query);
if (mounted && _searchQuery == query) {
setState(() {
_searchResults = results;
_isSearching = false;
});
}
} catch (e) {
if (mounted) setState(() => _isSearching = false);
}
}
Future<void> _loadMoreSeries() async {
// Prevent race conditions
if (_isLoading || !_hasMore || !mounted) return;
setState(() => _isLoading = true);
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
// Add timeout to prevent infinite loading state
final newSeries = await service
.getSeriesPaginated(
offset: _currentOffset,
limit: _pageSize,
)
.timeout(const Duration(seconds: 15));
if (mounted) {
setState(() {
_series.addAll(newSeries);
_currentOffset += _pageSize;
_hasMore = newSeries.length == _pageSize;
_isLoading = false;
});
}
} catch (e) {
debugPrint('Error loading series: $e');
if (mounted) {
setState(() {
_isLoading = false;
// Do NOT set _hasMore to false on error
});
}
}
}
Future<void> _refresh() async {
// Clear service cache to force fresh data
try {
final service =
await ref.read(mobileXtreamServiceProvider(widget.playlist).future);
service.clearCache();
} catch (_) {}
setState(() {
_series.clear();
_currentOffset = 0;
_hasMore = true;
_searchResults = null;
_searchQuery = '';
_searchController.clear();
_isLoading = false;
});
await _loadMoreSeries();
}
String? _formatRating(String? rating) {
if (rating == null || rating.isEmpty) return null;
final value = double.tryParse(rating);
if (value != null) {
return value.toStringAsFixed(1);
}
return rating;
}
/// On mobile, use direct URLs (no proxy needed)
String _getImageUrl(String? originalUrl) {
if (originalUrl == null || originalUrl.isEmpty) return '';
return originalUrl;
}
void _openSeries(Series series) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MobileSeriesDetailScreen(
series: series,
playlist: widget.playlist,
),
),
);
}
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
final settings = ref.watch(mobileSettingsProvider);
List<Series> displaySeries;
if (_searchQuery.isNotEmpty && _searchResults != null) {
displaySeries = _searchResults!;
} else {
displaySeries = settings.seriesKeywords.isEmpty
? _series
: _series
.where((s) => settings.matchesSeriesFilter(s.categoryName))
.toList();
}
// Hero Items (use filtered series)
final heroItems = displaySeries
.take(3)
.map(
(s) => HeroItem(
id: s.seriesId.toString(),
title: s.name,
imageUrl: _getImageUrl(s.cover),
subtitle: s.rating != null ? '${_formatRating(s.rating)} ★' : null,
onMoreInfo: () => _openSeries(s),
),
)
.toList();
return Container(
decoration: const BoxDecoration(gradient: AppColors.appleTvGradient),
child: PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
if (_searchQuery.isNotEmpty || _isSearching) {
_onSearchChanged(''); // clear search
_searchController.clear();
setState(() => _isSearchEditing = false);
return;
}
// Root View -> Show Exit Dialog
final shouldExit = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.grey[900],
title: const Text(
"Quitter l'application",
style: TextStyle(color: Colors.white),
),
content: const Text(
"Voulez-vous vraiment quitter l'application ?",
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
autofocus: true,
child: const Text(
'Annuler',
style: TextStyle(color: Colors.blueAccent),
),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text(
'Quitter',
style: TextStyle(color: Colors.redAccent),
),
),
],
),
);
if (shouldExit == true) {
SystemNavigator.pop();
}
},
child: SafeArea(
bottom: false,
child: RefreshIndicator(
onRefresh: _refresh,
color: AppColors.primary,
backgroundColor: AppColors.surface,
child: CustomScrollView(
controller: _scrollController,
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
// Hero Section (reduced height, moved above search)
if (_searchQuery.isEmpty && heroItems.isNotEmpty)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: SizedBox(
height: 180, // Reduced from 250
child: HeroCarousel(
items: heroItems,
onTap: (item) {
try {
final series = _series.firstWhere(
(s) => s.seriesId.toString() == item.id,
);
_openSeries(series);
} catch (e) {
// Fallback logic not critical
}
},
),
),
),
),
// Search Bar (moved below carousel)
SliverToBoxAdapter(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: TVFocusable(
scale: 1.0, // Disable scaling to prevent overflow
focusColor: Colors.white, // Solid white selection frame
onPressed: () {
setState(() => _isSearchEditing = true);
WidgetsBinding.instance.addPostFrameCallback((_) {
_searchFocusNode.requestFocus();
});
},
borderRadius: BorderRadius.circular(12),
child: Container(
height: 40,
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(12),
// Removed internal editing border here to prevent conflict and "inside frame" look
),
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(
cursorColor: Colors.white, // Extra safety
controller: _searchController,
focusNode: _searchFocusNode,
readOnly: !_isSearchEditing,
style: const TextStyle(
fontSize: 14,
color: AppColors.textPrimary,
),
decoration: const InputDecoration(
hintText: 'Rechercher une série...',
border: InputBorder.none,
focusedBorder: InputBorder
.none, // Explicitly remove focus border
enabledBorder: 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, // Reduced size further (was 4)
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: 0.7,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
if (index >= displaySeries.length) return null;
final series = displaySeries[index];
return MobilePosterCard(
title: series.name,
imageUrl: _getImageUrl(series.cover),
rating: _formatRating(series.rating),
placeholderIcon: Icons.tv,
onTap: () => _openSeries(series),
);
},
childCount: displaySeries.length,
),
),
),
if (_isLoading)
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(24),
child: Center(child: CircularProgressIndicator()),
),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,509 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart';
import '../../../providers/mobile_settings_providers.dart';
import '../../../widgets/tv_focusable.dart';
import '../../../../core/theme/app_colors.dart';
import '../screens/mobile_playlist_selection_screen.dart';
/// Simplified mobile settings tab - optimized for TV remote control
class MobileSettingsTab extends ConsumerStatefulWidget {
const MobileSettingsTab({super.key});
@override
ConsumerState<MobileSettingsTab> createState() => _MobileSettingsTabState();
}
class _MobileSettingsTabState extends ConsumerState<MobileSettingsTab> {
late TextEditingController _liveTvController;
late TextEditingController _moviesController;
late TextEditingController _seriesController;
bool _initialized = false;
bool _isRefreshingCache = false;
@override
void initState() {
super.initState();
_liveTvController = TextEditingController();
_moviesController = TextEditingController();
_seriesController = TextEditingController();
}
@override
void dispose() {
_liveTvController.dispose();
_moviesController.dispose();
_seriesController.dispose();
super.dispose();
}
void _syncControllers(MobileSettings settings) {
if (!_initialized) {
_liveTvController.text = settings.liveTvKeywords.join(', ');
_moviesController.text = settings.moviesKeywords.join(', ');
_seriesController.text = settings.seriesKeywords.join(', ');
_initialized = true;
}
}
List<String> _parseKeywords(String text) {
return text
.split(',')
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toList();
}
@override
Widget build(BuildContext context) {
final settings = ref.watch(mobileSettingsProvider);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!_initialized) _syncControllers(settings);
});
return SafeArea(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Header
Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
children: [
SizedBox(
width: 48,
height: 48,
// No decoration for free-floating logo
child: Image.asset(
'assets/images/logo_xtremflow.png',
fit: BoxFit.contain,
errorBuilder: (_, __, ___) => const Icon(
Icons.play_circle_filled,
color: AppColors.primary,
size: 28,
),
),
),
const SizedBox(width: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'XtremFlow Mobile',
style: GoogleFonts.inter(
fontSize: 18,
fontWeight: FontWeight.bold,
color: AppColors.textPrimary,
),
),
Text(
'Version 1.5.1',
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.textSecondary,
),
),
],
),
],
),
),
const SizedBox(height: 16),
_buildSettingItem(
icon: Icons.access_time,
title: 'Afficher l\'heure',
value: settings.showClock ? 'Activé' : 'Désactivé',
onTap: () => ref
.read(mobileSettingsProvider.notifier)
.toggleShowClock(!settings.showClock),
),
const SizedBox(height: 24),
// === LECTURE VIDEO ===
_buildSectionHeader('Lecture Vidéo'),
_buildSettingItem(
icon: Icons.memory,
title: 'Décodeur Vidéo',
subtitle: _getDecoderSubtitle(settings.decoderMode),
value: _getDecoderValue(settings.decoderMode),
onTap: () {
final modes = ['auto', 'mediacodec', 'no'];
final currentIndex = modes.indexOf(settings.decoderMode);
final nextIndex = (currentIndex + 1) % modes.length;
ref
.read(mobileSettingsProvider.notifier)
.setDecoderMode(modes[nextIndex]);
},
),
_buildSettingItem(
icon: Icons.speed,
title: 'Buffer (Cache)',
subtitle: settings.bufferDuration == 0
? 'Automatique'
: '${settings.bufferDuration} secondes',
value: settings.bufferDuration == 0
? 'Auto'
: '${settings.bufferDuration}s',
onTap: () {
final buffers = [0, 15, 30, 60];
final currentIndex = buffers.indexOf(settings.bufferDuration);
final nextIndex = (currentIndex + 1) % buffers.length;
ref
.read(mobileSettingsProvider.notifier)
.setBufferDuration(buffers[nextIndex]);
},
),
const SizedBox(height: 24),
// === FILTRES ===
_buildSectionHeader('Filtres de Contenu'),
_buildFilterInput(
label: 'TV en Direct',
hint: 'Ex: FR, HD, SPORT',
icon: Icons.live_tv,
currentKeywords: settings.liveTvKeywords,
controller: _liveTvController,
onChanged: (val) {
ref
.read(mobileSettingsProvider.notifier)
.setLiveTvKeywords(_parseKeywords(val));
},
),
_buildFilterInput(
label: 'Films',
hint: 'Ex: FR, VF, 4K',
icon: Icons.movie,
currentKeywords: settings.moviesKeywords,
controller: _moviesController,
onChanged: (val) {
ref
.read(mobileSettingsProvider.notifier)
.setMoviesKeywords(_parseKeywords(val));
},
),
_buildFilterInput(
label: 'Séries',
hint: 'Ex: FR, VF',
icon: Icons.tv,
currentKeywords: settings.seriesKeywords,
controller: _seriesController,
onChanged: (val) {
ref
.read(mobileSettingsProvider.notifier)
.setSeriesKeywords(_parseKeywords(val));
},
),
const SizedBox(height: 24),
// === CACHE ===
_buildSectionHeader('Cache'),
_buildSettingItem(
icon: _isRefreshingCache ? Icons.hourglass_empty : Icons.refresh,
title: 'Actualiser le cache',
subtitle: 'Recharge films, séries et EPG',
value: _isRefreshingCache ? '...' : 'Appuyer',
onTap: _isRefreshingCache ? null : _refreshCache,
),
const SizedBox(height: 24),
// === PLAYLIST ===
_buildSectionHeader('Playlist'),
_buildSettingItem(
icon: Icons.playlist_play,
title: 'Gérer les Playlists',
subtitle: 'Ajouter, modifier, supprimer',
value: '→',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
const MobilePlaylistSelectionScreen(manageMode: true),
),
);
},
),
const SizedBox(height: 100),
],
),
);
}
// === HELPER METHODS ===
String _getDecoderSubtitle(String mode) {
switch (mode) {
case 'auto':
return 'Automatique (Recommandé)';
case 'mediacodec':
return 'Matériel (Hardware)';
case 'no':
return 'Logiciel (Software)';
default:
return 'Automatique';
}
}
String _getDecoderValue(String mode) {
switch (mode) {
case 'auto':
return 'Auto';
case 'mediacodec':
return 'HW';
case 'no':
return 'SW';
default:
return 'Auto';
}
}
Future<void> _refreshCache() async {
setState(() => _isRefreshingCache = true);
try {
// final dir = await getApplicationDocumentsDirectory();
// final cacheStore = HiveCacheStore(dir.path);
// await cacheStore.clean();
await Future.delayed(const Duration(seconds: 1));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Cache actualisé ! Relancez l\'app pour recharger.'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
);
}
} finally {
if (mounted) setState(() => _isRefreshingCache = false);
}
}
// === UI BUILDERS ===
Widget _buildSectionHeader(String title) {
return Padding(
padding: const EdgeInsets.only(left: 4, bottom: 8, top: 8),
child: Text(
title.toUpperCase(),
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppColors.primary,
letterSpacing: 1.2,
),
),
);
}
Widget _buildSettingItem({
required IconData icon,
required String title,
String? subtitle,
required String value,
VoidCallback? onTap,
}) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: TVFocusable(
onPressed: onTap,
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Icon(icon, color: AppColors.primary, size: 24),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(
color: AppColors.textPrimary,
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
if (subtitle != null)
Text(
subtitle,
style: const TextStyle(
color: AppColors.textSecondary,
fontSize: 12,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: AppColors.primary.withOpacity(0.15),
borderRadius: BorderRadius.circular(8),
),
child: Text(
value,
style: const TextStyle(
color: AppColors.primary,
fontWeight: FontWeight.bold,
fontSize: 13,
),
),
),
],
),
),
),
);
}
Widget _buildFilterInput({
required String label,
required String hint,
required IconData icon,
required List<String> currentKeywords,
required TextEditingController controller,
required ValueChanged<String> onChanged,
}) {
final hasFilters = currentKeywords.isNotEmpty;
final subtitle = hasFilters
? currentKeywords.join(', ')
: 'Aucun filtre (Tout afficher)';
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: TVFocusable(
onPressed: () {
// Open keyboard dialog for text input
_showKeyboardDialog(label, controller, onChanged);
},
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Icon(icon, color: AppColors.primary, size: 24),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: const TextStyle(
color: AppColors.textPrimary,
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
Text(
subtitle,
style: TextStyle(
color: hasFilters
? AppColors.primary
: AppColors.textSecondary,
fontSize: 12,
fontWeight:
hasFilters ? FontWeight.w600 : FontWeight.normal,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
const Icon(Icons.edit, color: AppColors.textSecondary, size: 20),
],
),
),
),
);
}
void _showKeyboardDialog(
String label,
TextEditingController controller,
ValueChanged<String> onChanged,
) {
final tempController = TextEditingController(text: controller.text);
showDialog(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: AppColors.surface,
title: Text(
'Filtres $label',
style: const TextStyle(color: AppColors.textPrimary),
),
content: TextField(
controller: tempController,
autofocus: true,
style: const TextStyle(color: AppColors.textPrimary),
decoration: InputDecoration(
hintText: 'Séparez par des virgules',
hintStyle: const TextStyle(color: AppColors.textSecondary),
filled: true,
fillColor: AppColors.background,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Annuler'),
),
ElevatedButton(
onPressed: () {
controller.text = tempController.text;
onChanged(tempController.text);
Navigator.pop(ctx);
},
child: const Text('Sauvegarder'),
),
],
),
);
}
}