Resolve merge conflicts by accepting remote changes from origin/main

This commit is contained in:
Michael committed 2025-12-17 08:38:35 +01:00
commit 6d87ada2b8
5 files changed
+302 -256

No files matched your search

+139 -120
View File
@@ -5,20 +5,22 @@ import 'dart:math';
import 'package:shelf/shelf.dart'; import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart'; import 'package:shelf_router/shelf_router.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:xtremflow/core/models/playlist_config.dart'; import '../models/playlist_config.dart';
/// Active FFmpeg processes for VOD transcoding /// Active FFmpeg processes for VOD transcoding
final Map<String, Process> _vodProcesses = {}; final Map<String, Process> _vodProcesses = {};
/// Directory for temporary HLS segments /// Directory for temporary HLS segments
final Directory _hlsTempDir = Directory('${Directory.systemTemp.path}/xtremflow_streams'); final Directory _hlsTempDir =
Directory('${Directory.systemTemp.path}/xtremflow_streams');
/// Helper to resolve FFmpeg path (SYSTEM PATH vs Portable) /// Helper to resolve FFmpeg path (SYSTEM PATH vs Portable)
String _getFFmpegPath() { String _getFFmpegPath() {
if (Platform.isWindows) { if (Platform.isWindows) {
if (File('ffmpeg.exe').existsSync()) return 'ffmpeg.exe'; if (File('ffmpeg.exe').existsSync()) return 'ffmpeg.exe';
if (File('bin/ffmpeg.exe').existsSync()) return 'bin/ffmpeg.exe'; if (File('bin/ffmpeg.exe').existsSync()) return 'bin/ffmpeg.exe';
if (File('ffmpeg/bin/ffmpeg.exe').existsSync()) return 'ffmpeg/bin/ffmpeg.exe'; if (File('ffmpeg/bin/ffmpeg.exe').existsSync())
return 'ffmpeg/bin/ffmpeg.exe';
} }
return 'ffmpeg'; // Default to PATH return 'ffmpeg'; // Default to PATH
} }
@@ -30,6 +32,55 @@ Future<void> initStreaming() async {
} }
} }
/// Helper to resolve HTTP redirects and get final URL
/// Some IPTV servers return 302 redirects that FFmpeg doesn't follow properly
Future<String> _resolveRedirects(String url, {int maxRedirects = 5}) async {
String currentUrl = url;
final client = http.Client();
try {
for (int i = 0; i < maxRedirects; i++) {
final request = http.Request('GET', Uri.parse(currentUrl));
request.headers['User-Agent'] = 'VLC/3.0.18 LibVLC/3.0.18';
request.followRedirects = false;
final response = await client.send(request).timeout(
const Duration(seconds: 10),
onTimeout: () =>
throw TimeoutException('Redirect resolution timeout'),
);
// Check if it's a redirect (301, 302, 307, 308)
if (response.statusCode >= 300 && response.statusCode < 400) {
final location = response.headers['location'];
if (location != null && location.isNotEmpty) {
// Handle relative URLs
if (location.startsWith('/')) {
final uri = Uri.parse(currentUrl);
currentUrl = '${uri.scheme}://${uri.host}:${uri.port}$location';
} else {
currentUrl = location;
}
print('[Redirect] $i: $url -> $currentUrl');
await response.stream.drain();
continue;
}
}
// Not a redirect - we're done
await response.stream.drain();
break;
}
} catch (e) {
print('[Redirect] Error resolving redirects: $e');
// Return original URL if redirect resolution fails
} finally {
client.close();
}
return currentUrl;
}
/// Helper to get current playlist configuration (mocked for now, implies single user) /// Helper to get current playlist configuration (mocked for now, implies single user)
/// In a real scenario, this should come from the request session/context /// In a real scenario, this should come from the request session/context
PlaylistConfig? _getCurrentPlaylist(Request request) { PlaylistConfig? _getCurrentPlaylist(Request request) {
@@ -42,7 +93,8 @@ PlaylistConfig? _getCurrentPlaylist(Request request) {
// 1. LIVE TV HANDLER (Direct MPEG-TS Proxy) // 1. LIVE TV HANDLER (Direct MPEG-TS Proxy)
// ========================================== // ==========================================
Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPlaylist) { Handler createLiveStreamHandler(
Future<PlaylistConfig?> Function(Request) getPlaylist) {
final router = Router(); final router = Router();
// Route: /api/live/{streamId} (Catch all pattern to debug) // Route: /api/live/{streamId} (Catch all pattern to debug)
@@ -64,16 +116,21 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
return Response.internalServerError(body: 'No playlist configured'); return Response.internalServerError(body: 'No playlist configured');
} }
final targetUrl = '${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts'; // Use original URL - let FFmpeg handle HTTP redirects natively
// Manual redirect resolution consumes one-time tokens from IPTV servers
final targetUrl =
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
print('[Live] Streaming via FFmpeg: $targetUrl'); print('[Live] Streaming via FFmpeg: $targetUrl');
// Start FFmpeg to proxy and stabilize the stream // Start FFmpeg to proxy and stabilize the stream
// We use "-c copy" to avoid transcoding (Low CPU) but gain FFmpeg's network robustness // We use "-c copy" to avoid transcoding (Low CPU) but gain FFmpeg's network robustness
final ffmpegArgs = [ final ffmpegArgs = [
'-hide_banner', '-loglevel', 'error', '-hide_banner', '-loglevel', 'error',
'-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n', // Full headers to mimic a real video player
'-headers',
'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\nAccept: */*\r\nConnection: keep-alive\r\nReferer: ${playlist.dns}/\r\n',
// Robustness flags (Same as VOD) // HTTP redirect handling and robustness flags
'-reconnect', '1', '-reconnect', '1',
'-reconnect_at_eof', '1', '-reconnect_at_eof', '1',
'-reconnect_streamed', '1', '-reconnect_streamed', '1',
@@ -105,12 +162,12 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
process.stdout.listen( process.stdout.listen(
(data) => controller.add(data), (data) => controller.add(data),
onDone: () { onDone: () {
print('[Live] FFmpeg stream ended for $streamId'); print('[Live] FFmpeg stream ended for $streamId');
controller.close(); controller.close();
}, },
onError: (e) { onError: (e) {
print('[Live] FFmpeg stream error: $e'); print('[Live] FFmpeg stream error: $e');
controller.addError(e); controller.addError(e);
}, },
); );
@@ -146,53 +203,17 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
final _lastLogTime = <String, int>{}; final _lastLogTime = <String, int>{};
Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlaylist) { Handler createVodStreamHandler(
Future<PlaylistConfig?> Function(Request) getPlaylist) {
final router = Router(); final router = Router();
// Route: /api/vod/{streamId_with_ext}/playlist.m3u8 // Route: /api/vod/{streamId}/playlist.m3u8
router.get('/<filename>/playlist.m3u8', (Request request, String filename) async { router.get('/<streamId>/playlist.m3u8',
(Request request, String streamId) async {
final playlist = await getPlaylist(request); final playlist = await getPlaylist(request);
if (playlist == null) return Response.internalServerError(body: 'No playlist'); if (playlist == null)
return Response.internalServerError(body: 'No playlist');
// Parse streamId and extension from filename (e.g., "12345.mp4" -> id="12345", ext="mp4")
String streamId = filename;
String extension = ''; // No default yet
if (filename.contains('.')) {
final lastDotIndex = filename.lastIndexOf('.');
streamId = filename.substring(0, lastDotIndex);
extension = filename.substring(lastDotIndex + 1);
}
// If extension is missing, fetch it from API (Robustness fallback)
if (extension.isEmpty) {
print('[VOD] No extension provided for $streamId, fetching info...');
try {
final infoUrl = Uri.parse('${playlist.dns}/player_api.php?username=${playlist.username}&password=${playlist.password}&action=get_vod_info&vod_id=$streamId');
final response = await http.get(infoUrl);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data['movie_data'] != null && data['movie_data']['container_extension'] != null) {
extension = data['movie_data']['container_extension'].toString();
print('[VOD] Resolved extension: $extension');
}
}
} catch (e) {
print('[VOD] Failed to resolve extension: $e');
}
// Final fallback if API fails
if (extension.isEmpty) extension = 'mkv';
}
// Clean up old session if exists
if (_vodProcesses.containsKey(streamId)) {
print('[VOD] Killing previous session for $streamId');
_vodProcesses[streamId]?.kill();
_vodProcesses.remove(streamId);
}
// Prepare directory
final streamDir = Directory('${_hlsTempDir.path}/$streamId'); final streamDir = Directory('${_hlsTempDir.path}/$streamId');
// Check if existing session is healthy // Check if existing session is healthy
@@ -207,9 +228,10 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
if (content.contains('.ts')) { if (content.contains('.ts')) {
// Only log once per second to avoid spam // Only log once per second to avoid spam
final now = DateTime.now().millisecondsSinceEpoch; final now = DateTime.now().millisecondsSinceEpoch;
if (!_lastLogTime.containsKey(streamId) || (now - _lastLogTime[streamId]! > 2000)) { if (!_lastLogTime.containsKey(streamId) ||
print('[VOD] Reusing existing session for $streamId'); (now - _lastLogTime[streamId]! > 2000)) {
_lastLogTime[streamId] = now; print('[VOD] Reusing existing session for $streamId');
_lastLogTime[streamId] = now;
} }
// Serve existing playlist // Serve existing playlist
return Response.ok( return Response.ok(
@@ -242,8 +264,6 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
} }
} }
// Build Upstream URL based on content type // Build Upstream URL based on content type
// Check for type parameter in request URL (?type=series or ?type=movie) // Check for type parameter in request URL (?type=series or ?type=movie)
final contentType = request.url.queryParameters['type'] ?? 'movie'; final contentType = request.url.queryParameters['type'] ?? 'movie';
@@ -251,68 +271,71 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
// Only start FFmpeg if not already running // Only start FFmpeg if not already running
if (!_vodProcesses.containsKey(streamId)) { if (!_vodProcesses.containsKey(streamId)) {
// Prepare directory (Only for new session) // Prepare directory (Only for new session)
if (streamDir.existsSync()) { if (streamDir.existsSync()) {
streamDir.deleteSync(recursive: true); streamDir.deleteSync(recursive: true);
} }
streamDir.createSync(recursive: true); streamDir.createSync(recursive: true);
final targetUrl = '${playlist.dns}/$basePath/${playlist.username}/${playlist.password}/$streamId.$extension'; final targetUrl =
print('[VOD] Starting Transcode ($contentType): $targetUrl'); '${playlist.dns}/$basePath/${playlist.username}/${playlist.password}/$streamId.mkv';
print('[VOD] Starting Transcode ($contentType): $targetUrl');
// Start FFmpeg // Start FFmpeg
final ffmpegArgs = [ final ffmpegArgs = [
'-hide_banner', '-loglevel', 'error', '-hide_banner', '-loglevel', 'error',
'-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n', '-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
// Robustness for network streams // Robustness for network streams
'-reconnect', '1', '-reconnect', '1',
'-reconnect_at_eof', '1', '-reconnect_at_eof', '1',
'-reconnect_streamed', '1', '-reconnect_streamed', '1',
'-reconnect_delay_max', '5', '-reconnect_delay_max', '5',
'-rw_timeout', '15000000', '-rw_timeout', '15000000',
'-analyzeduration', '2000000', // Reduced from 10M to 2M for faster start '-analyzeduration',
'-probesize', '2000000', // Reduced from 10M to 2M for faster start '2000000', // Reduced from 10M to 2M for faster start
'-probesize', '2000000', // Reduced from 10M to 2M for faster start
'-i', targetUrl, '-i', targetUrl,
// Video: H.264 Ultrafast (Low CPU) // Video: H.264 Ultrafast (Low CPU)
'-c:v', 'libx264', '-c:v', 'libx264',
'-preset', 'ultrafast', '-preset', 'ultrafast',
'-tune', 'zerolatency', // Optimize for low latency startup '-tune', 'zerolatency', // Optimize for low latency startup
'-tune', 'fastdecode', '-tune', 'fastdecode',
'-crf', '23', '-crf', '23',
'-maxrate', '3000k', '-maxrate', '3000k',
'-bufsize', '6000k', '-bufsize', '6000k',
'-pix_fmt', 'yuv420p', '-pix_fmt', 'yuv420p',
'-threads', '0', '-threads', '0',
// Audio: AAC (Browser compatible, improved quality) // Audio: AAC (Browser compatible, improved quality)
'-c:a', 'aac', '-c:a', 'aac',
'-b:a', '192k', '-b:a', '192k',
'-ar', '48000', '-ar', '48000',
// Advanced Audio Filtering: // Advanced Audio Filtering:
// 1. "pan": Downmix 5.1/7.1 to Stereo with center mix (dialogue) boosted. // 1. "pan": Downmix 5.1/7.1 to Stereo with center mix (dialogue) boosted.
// 2. "dynaudnorm": Dynamic Audio Normalizer to boost quiet dialogue and limit loud explosions (Night Mode effect). // 2. "dynaudnorm": Dynamic Audio Normalizer to boost quiet dialogue and limit loud explosions (Night Mode effect).
'-af', 'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15', '-af',
'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15',
'-f', 'hls',
'-hls_time', '4',
'-hls_list_size', '0',
'-hls_playlist_type',
'event', // Event type allows immediate playback while transcoding
'-hls_allow_cache', '1',
'-hls_segment_type', 'mpegts',
'-hls_segment_filename', '${streamDir.path}/segment_%03d.ts',
'-start_number', '0',
'-f', 'hls', // Write playlist to stdout or file? File is easier for static serving
'-hls_time', '4', '${streamDir.path}/playlist.m3u8',
'-hls_list_size', '0', ];
'-hls_playlist_type', 'event', // Event type allows immediate playback while transcoding
'-hls_allow_cache', '1',
'-hls_segment_type', 'mpegts',
'-hls_segment_filename', '${streamDir.path}/segment_%03d.ts',
'-start_number', '0',
// Write playlist to stdout or file? File is easier for static serving final ffmpegPath = _getFFmpegPath();
'${streamDir.path}/playlist.m3u8', Process.start(ffmpegPath, ffmpegArgs).then((process) {
];
final ffmpegPath = _getFFmpegPath();
Process.start(ffmpegPath, ffmpegArgs).then((process) {
_vodProcesses[streamId] = process; _vodProcesses[streamId] = process;
process.stderr.transform(utf8.decoder).listen((data) { process.stderr.transform(utf8.decoder).listen((data) {
@@ -337,7 +360,8 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
} }
if (!playlistFile.existsSync()) { if (!playlistFile.existsSync()) {
return Response.internalServerError(body: 'Timeout waiting for transcoder'); return Response.internalServerError(
body: 'Timeout waiting for transcoder');
} }
return Response.ok( return Response.ok(
@@ -350,14 +374,9 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
); );
}); });
// Route: /api/vod/{filename}/segment_{n}.ts (Serve segments) // Route: /api/vod/{streamId}/segment_{n}.ts (Serve segments)
router.get('/<filename>/<segment>', (Request request, String filename, String segment) async { router.get('/<streamId>/<segment>',
// Extract streamId from filename to find the directory (Request request, String streamId, String segment) async {
String streamId = filename;
if (filename.contains('.')) {
streamId = filename.substring(0, filename.lastIndexOf('.'));
}
final file = File('${_hlsTempDir.path}/$streamId/$segment'); final file = File('${_hlsTempDir.path}/$streamId/$segment');
if (!file.existsSync()) { if (!file.existsSync()) {
+52
View File
@@ -0,0 +1,52 @@
/// Pure Dart model for Xtream Codes playlist configuration
/// This is a server-side copy without Hive/Equatable dependencies
class PlaylistConfig {
final String id;
final String name;
/// Xtream server URL (without trailing slash)
final String dns;
final String username;
/// Xtream password
final String password;
final DateTime createdAt;
final bool isActive;
const PlaylistConfig({
required this.id,
required this.name,
required this.dns,
required this.username,
required this.password,
required this.createdAt,
this.isActive = true,
});
/// Creates a copy of this playlist with updated fields
PlaylistConfig copyWith({
String? id,
String? name,
String? dns,
String? username,
String? password,
DateTime? createdAt,
bool? isActive,
}) {
return PlaylistConfig(
id: id ?? this.id,
name: name ?? this.name,
dns: dns ?? this.dns,
username: username ?? this.username,
password: password ?? this.password,
createdAt: createdAt ?? this.createdAt,
isActive: isActive ?? this.isActive,
);
}
/// Generate Xtream API base URL
String get apiBaseUrl => '$dns/player_api.php';
}
+100 -82
View File
@@ -10,7 +10,7 @@ import 'package:args/args.dart';
import 'database/database.dart'; import 'database/database.dart';
import 'models/user.dart'; import 'models/user.dart';
import 'models/playlist.dart'; import 'models/playlist.dart';
import 'package:xtremflow/core/models/playlist_config.dart'; import 'models/playlist_config.dart';
import 'api/auth_handler.dart'; import 'api/auth_handler.dart';
import 'api/users_handler.dart'; import 'api/users_handler.dart';
import 'api/playlists_handler.dart'; import 'api/playlists_handler.dart';
@@ -49,17 +49,26 @@ void main(List<String> args) async {
// Auth endpoints // Auth endpoints
..mount('/api/auth', authHandler.router) ..mount('/api/auth', authHandler.router)
// Playlists endpoints // Playlists endpoints
..mount('/api/playlists', const Pipeline() ..mount(
.addMiddleware(authMiddleware(db)) '/api/playlists',
.addHandler(playlistsHandler.router.call),) const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(playlistsHandler.router.call),
)
// Users endpoints // Users endpoints
..mount('/api/users', const Pipeline() ..mount(
.addMiddleware(authMiddleware(db)) '/api/users',
.addHandler(usersHandler.router.call),) const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(usersHandler.router.call),
)
// Settings endpoints // Settings endpoints
..mount('/api/settings', const Pipeline() ..mount(
.addMiddleware(authMiddleware(db)) '/api/settings',
.addHandler(settingsHandler.router.call),); const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(settingsHandler.router.call),
);
// Initialize Cleanup Service // Initialize Cleanup Service
final cleanupService = CleanupService(); final cleanupService = CleanupService();
@@ -70,27 +79,31 @@ void main(List<String> args) async {
cleanupService.start(); cleanupService.start();
// Admin Routes (protected) // Admin Routes (protected)
apiRouter.mount('/api/admin', const Pipeline() apiRouter.mount(
.addMiddleware(authMiddleware(db)) '/api/admin',
.addHandler((Request request) { const Pipeline()
final router = Router(); .addMiddleware(authMiddleware(db))
.addHandler((Request request) {
final router = Router();
// POST /api/admin/purge // POST /api/admin/purge
router.post('/purge', (Request req) async { router.post('/purge', (Request req) async {
final user = req.context['user'] as User?; final user = req.context['user'] as User?;
if (user == null || !user.isAdmin) { if (user == null || !user.isAdmin) {
return Response.forbidden(jsonEncode({'error': 'Admin access required'})); return Response.forbidden(
} jsonEncode({'error': 'Admin access required'}));
}
final result = await cleanupService.runCleanup(); final result = await cleanupService.runCleanup();
return Response.ok( return Response.ok(
jsonEncode(result), jsonEncode(result),
headers: {'content-type': 'application/json'}, headers: {'content-type': 'application/json'},
); );
}); });
return router(request); return router(request);
}),); }),
);
// Create static handler // Create static handler
final baseStaticHandler = createStaticHandler( final baseStaticHandler = createStaticHandler(
@@ -109,48 +122,52 @@ void main(List<String> args) async {
path == 'index.html' || path == 'index.html' ||
path.endsWith('.js') || path.endsWith('.js') ||
path.endsWith('.json')) { path.endsWith('.json')) {
return response.change(headers: { return response.change(
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0', headers: {
'Pragma': 'no-cache', 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
'Expires': '0', 'Pragma': 'no-cache',
},); 'Expires': '0',
},
);
} }
// Allow aggressive caching for hashed assets // Allow aggressive caching for hashed assets
return response.change(headers: { return response.change(
'Cache-Control': 'public, max-age=86400', headers: {
},); 'Cache-Control': 'public, max-age=86400',
},
);
} }
// Helper to get playlist from request // Helper to get playlist from request
Future<PlaylistConfig?> getPlaylist(Request request) async { Future<PlaylistConfig?> getPlaylist(Request request) async {
Playlist? playlist; Playlist? playlist;
final user = request.context['user'] as User?; final user = request.context['user'] as User?;
if (user != null) { if (user != null) {
final playlists = db.getPlaylists(user.id); final playlists = db.getPlaylists(user.id);
if (playlists.isNotEmpty) playlist = playlists.first; if (playlists.isNotEmpty) playlist = playlists.first;
} else { } else {
// Fallback: Try to find a playlist for any user if no specific user is logged in // Fallback: Try to find a playlist for any user if no specific user is logged in
final users = db.getAllUsers(); final users = db.getAllUsers();
if (users.isNotEmpty) { if (users.isNotEmpty) {
final playlists = db.getPlaylists(users[0].id); final playlists = db.getPlaylists(users[0].id);
if (playlists.isNotEmpty) playlist = playlists.first; if (playlists.isNotEmpty) playlist = playlists.first;
} }
} }
if (playlist != null) { if (playlist != null) {
return PlaylistConfig( return PlaylistConfig(
id: playlist.id, id: playlist.id,
name: playlist.name, name: playlist.name,
dns: playlist.serverUrl, dns: playlist.serverUrl,
username: playlist.username, username: playlist.username,
password: playlist.password, password: playlist.password,
createdAt: playlist.createdAt, createdAt: playlist.createdAt,
isActive: true, isActive: true,
); );
} }
return null; return null;
} }
// Create Streaming Router (Mount handlers on correct paths) // Create Streaming Router (Mount handlers on correct paths)
@@ -160,20 +177,20 @@ void main(List<String> args) async {
// Main handler with API proxy and NEW Streaming Handlers // Main handler with API proxy and NEW Streaming Handlers
final handler = Cascade() final handler = Cascade()
.add(apiRouter.call) /* Standard API endpoints */ .add(apiRouter.call) /* Standard API endpoints */
.add(_createXtreamProxyHandler()) /* Keep for general API calls */ .add(_createXtreamProxyHandler()) /* Keep for general API calls */
.add(streamingRouter.call) /* Streaming endpoints */ .add(streamingRouter.call) /* Streaming endpoints */
.add(staticHandler) .add(staticHandler)
.handler; .handler;
// Add middleware // Add middleware
final pipeline = const Pipeline() final pipeline = const Pipeline()
.addMiddleware(logRequests()) .addMiddleware(logRequests())
.addMiddleware(securityHeadersMiddleware()) .addMiddleware(securityHeadersMiddleware())
.addMiddleware(honeypotMiddleware()) .addMiddleware(honeypotMiddleware())
.addMiddleware(rateLimitMiddleware()) .addMiddleware(rateLimitMiddleware())
.addMiddleware(_corsMiddleware()) .addMiddleware(_corsMiddleware())
.addHandler(handler); .addHandler(handler);
// Start server // Start server
final server = await shelf_io.serve( final server = await shelf_io.serve(
@@ -194,8 +211,6 @@ void main(List<String> args) async {
}); });
} }
/// CORS middleware to allow cross-origin requests /// CORS middleware to allow cross-origin requests
Middleware _corsMiddleware() { Middleware _corsMiddleware() {
return (Handler handler) { return (Handler handler) {
@@ -265,15 +280,17 @@ Handler _createXtreamProxyHandler() {
http.Response response; http.Response response;
if (request.method == 'GET') { if (request.method == 'GET') {
response = await http.get(targetUrl, headers: proxyHeaders).timeout( response = await http.get(targetUrl, headers: proxyHeaders).timeout(
const Duration(seconds: 30), const Duration(seconds: 30),
onTimeout: () => http.Response('Request timeout', 504), onTimeout: () => http.Response('Request timeout', 504),
); );
} else if (request.method == 'POST') { } else if (request.method == 'POST') {
final body = await request.readAsString(); final body = await request.readAsString();
response = await http.post(targetUrl, headers: proxyHeaders, body: body).timeout( response = await http
const Duration(seconds: 30), .post(targetUrl, headers: proxyHeaders, body: body)
onTimeout: () => http.Response('Request timeout', 504), .timeout(
); const Duration(seconds: 30),
onTimeout: () => http.Response('Request timeout', 504),
);
} else { } else {
return Response(405, body: 'Method not allowed'); return Response(405, body: 'Method not allowed');
} }
@@ -282,7 +299,8 @@ Handler _createXtreamProxyHandler() {
response.statusCode, response.statusCode,
body: response.bodyBytes, body: response.bodyBytes,
headers: { headers: {
'content-type': response.headers['content-type'] ?? 'application/json', 'content-type':
response.headers['content-type'] ?? 'application/json',
'access-control-allow-origin': '*', 'access-control-allow-origin': '*',
}, },
); );
@@ -17,8 +17,8 @@ class XtreamService {
XtreamService() { XtreamService() {
_dio = Dio(BaseOptions( _dio = Dio(BaseOptions(
connectTimeout: const Duration(seconds: 60), connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 60), receiveTimeout: const Duration(seconds: 15),
),); ),);
// Setup caching for API responses // Setup caching for API responses
@@ -70,19 +70,18 @@ class XtreamService {
String getVodStreamUrl(String streamId, String containerExtension) { String getVodStreamUrl(String streamId, String containerExtension) {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
// Pass extension to backend for correct upstream URL construction // Point to new dedicated VOD API (HLS playlist)
final baseUrl = html.window.location.origin; final baseUrl = html.window.location.origin;
return '$baseUrl/api/vod/$streamId.$containerExtension/playlist.m3u8'; return '$baseUrl/api/vod/$streamId/playlist.m3u8';
} }
/// Generate stream URL for series episodes /// Generate stream URL for series episodes
String getSeriesStreamUrl(String streamId, String containerExtension) { String getSeriesStreamUrl(String streamId, String containerExtension) {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
// Pass extension to backend for correct upstream URL construction // Point to new dedicated VOD API (HLS playlist) with series type
// And include type parameter for correct path handling (movie vs series)
final baseUrl = html.window.location.origin; final baseUrl = html.window.location.origin;
return '$baseUrl/api/vod/$streamId.$containerExtension/playlist.m3u8?type=series'; return '$baseUrl/api/vod/$streamId/playlist.m3u8?type=series';
} }
/// Authenticate and get server info /// Authenticate and get server info
+5 -47
View File
@@ -1,48 +1,6 @@
# XtremFlow Development # Fix EPG Overlay Interaction
Context: Developing a high-performance IPTV Web App with Flutter and Docker. - [ ] Analyze `player_screen.dart` for overlap issues.
- [ ] Reproduce/Locate the code responsible for EPG overlay.
Current Focus: Resuming development after environment fix. - [ ] Fix the touch event propagation issue.
- [x] Verify the fix.
Master Plan:
## 🧹 Housekeeping
- [x] Commit pending changes in `xtream_service.dart` (Timeout increase).
## 🎥 Player Debugging (CRITICAL)
- [ ] **Fix VOD Playback**: User reports VOD is not playing.
- [x] Check VOD URL generation in `xtream_service.dart`. (Fixed upstream URL to include extension)
- [x] Check `web/player.html` compatibility with VOD formats. (HLS/Direct support verified)
- [x] Verify `PlayerScreen` logic for VOD StreamType. (Correctly passes extension)
- [x] Update `streaming_handler.dart` to handle extensions dynamically. (Done)
- [x] Rebuild Docker Image to apply backend changes.
- [x] Restart Docker containers.
- [x] Verify VOD playback. (Failed)
- [ ] **Phase 2 Debugging**:
- [x] Analyze Docker logs for FFmpeg/Proxy errors. (Found 404/4XX on MKV)
- [x] Implement backend auto-detection of extension via Xtream API.
- [x] Restart Docker containers.
- [x] Restart Docker containers.
- [x] Verify VOD playback. (Backend Fallback active)
- [ ] **Clean Reinstall** (User Request):
- [x] Stop and Remove Containers (`down`).
- [/] Force Rebuild and Start (`up --build`).
## 🎥 Player Improvements (Active Context)
- [ ] Review `player_screen.dart` controls logic.
- [ ] **Goal**: Enhance VOD/Series controls vs Live TV controls.
- *Context*: User wants skip/prev buttons to change channels only for Live TV? Need clarification on VOD behavior.
## 📦 Backlog
- [ ] Resolve Git Conflict ModuleNotFoundError: No module named 'rich' (Done)
- [x] Update Docker Image (Timeout increase)
## 🔧 Git Maintenance
- [x] **Resolve Conflicts**:
- [x] `bin/api/streaming_handler.dart`
- [x] `lib/features/iptv/services/xtream_service.dart`