mirror of
https://github.com/R0m1k3/xtremflow.git
synced 2026-10-24 07:28:05 +02:00
fix: add Dart-pure PlaylistConfig for server and fix imports
This commit is contained in:
1 parent
3486e15334
commit
01d522613f
3 files changed
+270
-188
No files matched your search
+103
-91
@@ -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
|
||||||
}
|
}
|
||||||
@@ -42,13 +44,14 @@ 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)
|
||||||
router.get('/<streamId|.*>', (Request request, String streamId) async {
|
router.get('/<streamId|.*>', (Request request, String streamId) async {
|
||||||
print('[Live] Incoming request for streamId: $streamId');
|
print('[Live] Incoming request for streamId: $streamId');
|
||||||
|
|
||||||
// Remove .ts extension if present
|
// Remove .ts extension if present
|
||||||
// Remove extension if present (handle both .ts and .m3u8 just in case)
|
// Remove extension if present (handle both .ts and .m3u8 just in case)
|
||||||
if (streamId.endsWith('.ts')) {
|
if (streamId.endsWith('.ts')) {
|
||||||
@@ -58,13 +61,14 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
|
|||||||
}
|
}
|
||||||
|
|
||||||
final playlist = await getPlaylist(request);
|
final playlist = await getPlaylist(request);
|
||||||
|
|
||||||
if (playlist == null) {
|
if (playlist == null) {
|
||||||
print('[Live] Error: No playlist found');
|
print('[Live] Error: No playlist found');
|
||||||
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';
|
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
|
||||||
@@ -72,7 +76,7 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
|
|||||||
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 flags (Same as VOD)
|
// Robustness flags (Same as VOD)
|
||||||
'-reconnect', '1',
|
'-reconnect', '1',
|
||||||
'-reconnect_at_eof', '1',
|
'-reconnect_at_eof', '1',
|
||||||
@@ -81,9 +85,9 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
|
|||||||
'-rw_timeout', '15000000',
|
'-rw_timeout', '15000000',
|
||||||
'-analyzeduration', '5000000', // Faster probe for live
|
'-analyzeduration', '5000000', // Faster probe for live
|
||||||
'-probesize', '5000000',
|
'-probesize', '5000000',
|
||||||
|
|
||||||
'-i', targetUrl,
|
'-i', targetUrl,
|
||||||
|
|
||||||
'-c', 'copy', // Direct stream copy (Very low CPU)
|
'-c', 'copy', // Direct stream copy (Very low CPU)
|
||||||
'-f', 'mpegts',
|
'-f', 'mpegts',
|
||||||
'pipe:1', // Output to stdout
|
'pipe:1', // Output to stdout
|
||||||
@@ -92,7 +96,7 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
|
|||||||
try {
|
try {
|
||||||
final ffmpegPath = _getFFmpegPath();
|
final ffmpegPath = _getFFmpegPath();
|
||||||
final process = await Process.start(ffmpegPath, ffmpegArgs);
|
final process = await Process.start(ffmpegPath, ffmpegArgs);
|
||||||
|
|
||||||
// Cleanup handling: Kill FFmpeg when client disconnects
|
// Cleanup handling: Kill FFmpeg when client disconnects
|
||||||
final controller = StreamController<List<int>>(
|
final controller = StreamController<List<int>>(
|
||||||
onCancel: () {
|
onCancel: () {
|
||||||
@@ -100,20 +104,20 @@ Handler createLiveStreamHandler(Future<PlaylistConfig?> Function(Request) getPla
|
|||||||
process.kill();
|
process.kill();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Pipe stdout to controller
|
// Pipe stdout to controller
|
||||||
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);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Log errors
|
// Log errors
|
||||||
process.stderr.transform(utf8.decoder).listen((data) {
|
process.stderr.transform(utf8.decoder).listen((data) {
|
||||||
print('[FFmpeg Live $streamId] $data');
|
print('[FFmpeg Live $streamId] $data');
|
||||||
@@ -146,20 +150,23 @@ 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}/playlist.m3u8
|
// Route: /api/vod/{streamId}/playlist.m3u8
|
||||||
router.get('/<streamId>/playlist.m3u8', (Request request, String streamId) 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');
|
||||||
|
|
||||||
final streamDir = Directory('${_hlsTempDir.path}/$streamId');
|
final streamDir = Directory('${_hlsTempDir.path}/$streamId');
|
||||||
|
|
||||||
// Check if existing session is healthy
|
// Check if existing session is healthy
|
||||||
if (_vodProcesses.containsKey(streamId)) {
|
if (_vodProcesses.containsKey(streamId)) {
|
||||||
final existingProcess = _vodProcesses[streamId]!;
|
final existingProcess = _vodProcesses[streamId]!;
|
||||||
|
|
||||||
// Check if process is still running by checking if playlist exists and has content
|
// Check if process is still running by checking if playlist exists and has content
|
||||||
final playlistFile = File('${streamDir.path}/playlist.m3u8');
|
final playlistFile = File('${streamDir.path}/playlist.m3u8');
|
||||||
if (playlistFile.existsSync()) {
|
if (playlistFile.existsSync()) {
|
||||||
@@ -168,9 +175,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(
|
||||||
@@ -183,7 +191,7 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Playlist missing or empty - process likely failed, clean up
|
// Playlist missing or empty - process likely failed, clean up
|
||||||
print('[VOD] Cleaning up stale session for $streamId');
|
print('[VOD] Cleaning up stale session for $streamId');
|
||||||
try {
|
try {
|
||||||
@@ -192,7 +200,7 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
|
|||||||
// Process may already be dead
|
// Process may already be dead
|
||||||
}
|
}
|
||||||
_vodProcesses.remove(streamId);
|
_vodProcesses.remove(streamId);
|
||||||
|
|
||||||
// Clean up directory
|
// Clean up directory
|
||||||
if (streamDir.existsSync()) {
|
if (streamDir.existsSync()) {
|
||||||
try {
|
try {
|
||||||
@@ -203,82 +211,84 @@ 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';
|
||||||
final basePath = contentType == 'series' ? 'series' : 'movie';
|
final basePath = contentType == 'series' ? 'series' : 'movie';
|
||||||
|
|
||||||
// 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.mkv';
|
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
|
|
||||||
'-reconnect', '1',
|
|
||||||
'-reconnect_at_eof', '1',
|
|
||||||
'-reconnect_streamed', '1',
|
|
||||||
'-reconnect_delay_max', '5',
|
|
||||||
'-rw_timeout', '15000000',
|
|
||||||
'-analyzeduration', '2000000', // Reduced from 10M to 2M for faster start
|
|
||||||
'-probesize', '2000000', // Reduced from 10M to 2M for faster start
|
|
||||||
|
|
||||||
'-i', targetUrl,
|
|
||||||
|
|
||||||
// Video: H.264 Ultrafast (Low CPU)
|
|
||||||
'-c:v', 'libx264',
|
|
||||||
'-preset', 'ultrafast',
|
|
||||||
'-tune', 'zerolatency', // Optimize for low latency startup
|
|
||||||
'-tune', 'fastdecode',
|
|
||||||
'-crf', '23',
|
|
||||||
'-maxrate', '3000k',
|
|
||||||
'-bufsize', '6000k',
|
|
||||||
'-pix_fmt', 'yuv420p',
|
|
||||||
'-threads', '0',
|
|
||||||
|
|
||||||
// Audio: AAC (Browser compatible, improved quality)
|
// Robustness for network streams
|
||||||
'-c:a', 'aac',
|
'-reconnect', '1',
|
||||||
'-b:a', '192k',
|
'-reconnect_at_eof', '1',
|
||||||
'-ar', '48000',
|
'-reconnect_streamed', '1',
|
||||||
|
'-reconnect_delay_max', '5',
|
||||||
// Advanced Audio Filtering:
|
'-rw_timeout', '15000000',
|
||||||
// 1. "pan": Downmix 5.1/7.1 to Stereo with center mix (dialogue) boosted.
|
'-analyzeduration',
|
||||||
// 2. "dynaudnorm": Dynamic Audio Normalizer to boost quiet dialogue and limit loud explosions (Night Mode effect).
|
'2000000', // Reduced from 10M to 2M for faster start
|
||||||
'-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',
|
'-probesize', '2000000', // Reduced from 10M to 2M for faster start
|
||||||
|
|
||||||
|
'-i', targetUrl,
|
||||||
|
|
||||||
'-f', 'hls',
|
// Video: H.264 Ultrafast (Low CPU)
|
||||||
'-hls_time', '4',
|
'-c:v', 'libx264',
|
||||||
'-hls_list_size', '0',
|
'-preset', 'ultrafast',
|
||||||
'-hls_playlist_type', 'event', // Event type allows immediate playback while transcoding
|
'-tune', 'zerolatency', // Optimize for low latency startup
|
||||||
'-hls_allow_cache', '1',
|
'-tune', 'fastdecode',
|
||||||
'-hls_segment_type', 'mpegts',
|
'-crf', '23',
|
||||||
'-hls_segment_filename', '${streamDir.path}/segment_%03d.ts',
|
'-maxrate', '3000k',
|
||||||
'-start_number', '0',
|
'-bufsize', '6000k',
|
||||||
|
'-pix_fmt', 'yuv420p',
|
||||||
// Write playlist to stdout or file? File is easier for static serving
|
'-threads', '0',
|
||||||
'${streamDir.path}/playlist.m3u8',
|
|
||||||
];
|
|
||||||
|
|
||||||
final ffmpegPath = _getFFmpegPath();
|
// Audio: AAC (Browser compatible, improved quality)
|
||||||
Process.start(ffmpegPath, ffmpegArgs).then((process) {
|
'-c:a', 'aac',
|
||||||
|
'-b:a', '192k',
|
||||||
|
'-ar', '48000',
|
||||||
|
|
||||||
|
// Advanced Audio Filtering:
|
||||||
|
// 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).
|
||||||
|
'-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',
|
||||||
|
|
||||||
|
// Write playlist to stdout or file? File is easier for static serving
|
||||||
|
'${streamDir.path}/playlist.m3u8',
|
||||||
|
];
|
||||||
|
|
||||||
|
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) {
|
||||||
// Log only major errors or startup info to keep logs clean(er)
|
// Log only major errors or startup info to keep logs clean(er)
|
||||||
// or keep verbose if debugging
|
// or keep verbose if debugging
|
||||||
print('[FFmpeg $streamId] $data');
|
print('[FFmpeg $streamId] $data');
|
||||||
});
|
});
|
||||||
|
|
||||||
process.exitCode.then((code) {
|
process.exitCode.then((code) {
|
||||||
@@ -297,7 +307,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(
|
||||||
@@ -311,9 +322,10 @@ Handler createVodStreamHandler(Future<PlaylistConfig?> Function(Request) getPlay
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Route: /api/vod/{streamId}/segment_{n}.ts (Serve segments)
|
// Route: /api/vod/{streamId}/segment_{n}.ts (Serve segments)
|
||||||
router.get('/<streamId>/<segment>', (Request request, String streamId, String segment) async {
|
router.get('/<streamId>/<segment>',
|
||||||
|
(Request request, String streamId, String segment) async {
|
||||||
final file = File('${_hlsTempDir.path}/$streamId/$segment');
|
final file = File('${_hlsTempDir.path}/$streamId/$segment');
|
||||||
|
|
||||||
if (!file.existsSync()) {
|
if (!file.existsSync()) {
|
||||||
return Response.notFound('Segment not found');
|
return Response.notFound('Segment not found');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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';
|
||||||
|
}
|
||||||
+115
-97
@@ -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';
|
||||||
@@ -25,7 +25,7 @@ void main(List<String> args) async {
|
|||||||
final parser = ArgParser()
|
final parser = ArgParser()
|
||||||
..addOption('port', abbr: 'p', defaultsTo: '8089')
|
..addOption('port', abbr: 'p', defaultsTo: '8089')
|
||||||
..addOption('path', defaultsTo: '/app/web');
|
..addOption('path', defaultsTo: '/app/web');
|
||||||
|
|
||||||
final result = parser.parse(args);
|
final result = parser.parse(args);
|
||||||
final port = int.parse(result['port']);
|
final port = int.parse(result['port']);
|
||||||
final webPath = result['path'];
|
final webPath = result['path'];
|
||||||
@@ -49,48 +49,61 @@ 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();
|
||||||
cleanupService.addTarget(Directory.systemTemp);
|
cleanupService.addTarget(Directory.systemTemp);
|
||||||
cleanupService.addTarget(Directory('/app/data/logs'));
|
cleanupService.addTarget(Directory('/app/data/logs'));
|
||||||
cleanupService.addTarget(Directory('/app/data/tmp'));
|
cleanupService.addTarget(Directory('/app/data/tmp'));
|
||||||
|
|
||||||
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) {
|
||||||
// POST /api/admin/purge
|
final router = Router();
|
||||||
router.post('/purge', (Request req) async {
|
|
||||||
final user = req.context['user'] as User?;
|
// POST /api/admin/purge
|
||||||
if (user == null || !user.isAdmin) {
|
router.post('/purge', (Request req) async {
|
||||||
return Response.forbidden(jsonEncode({'error': 'Admin access required'}));
|
final user = req.context['user'] as User?;
|
||||||
}
|
if (user == null || !user.isAdmin) {
|
||||||
|
return Response.forbidden(
|
||||||
final result = await cleanupService.runCleanup();
|
jsonEncode({'error': 'Admin access required'}));
|
||||||
return Response.ok(
|
}
|
||||||
jsonEncode(result),
|
|
||||||
headers: {'content-type': 'application/json'},
|
final result = await cleanupService.runCleanup();
|
||||||
);
|
return Response.ok(
|
||||||
});
|
jsonEncode(result),
|
||||||
|
headers: {'content-type': 'application/json'},
|
||||||
return router(request);
|
);
|
||||||
}),);
|
});
|
||||||
|
|
||||||
|
return router(request);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
// Create static handler
|
// Create static handler
|
||||||
final baseStaticHandler = createStaticHandler(
|
final baseStaticHandler = createStaticHandler(
|
||||||
@@ -102,55 +115,59 @@ void main(List<String> args) async {
|
|||||||
// Wrap static handler to enforce cache policies
|
// Wrap static handler to enforce cache policies
|
||||||
FutureOr<Response> staticHandler(Request request) async {
|
FutureOr<Response> staticHandler(Request request) async {
|
||||||
final response = await baseStaticHandler(request);
|
final response = await baseStaticHandler(request);
|
||||||
|
|
||||||
// Disable cache for entry points to ensure updates are seen immediately
|
// Disable cache for entry points to ensure updates are seen immediately
|
||||||
final path = request.url.path;
|
final path = request.url.path;
|
||||||
if (path.isEmpty ||
|
if (path.isEmpty ||
|
||||||
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?;
|
|
||||||
if (user != null) {
|
|
||||||
final playlists = db.getPlaylists(user.id);
|
|
||||||
if (playlists.isNotEmpty) playlist = playlists.first;
|
|
||||||
} else {
|
|
||||||
// Fallback: Try to find a playlist for any user if no specific user is logged in
|
|
||||||
final users = db.getAllUsers();
|
|
||||||
if (users.isNotEmpty) {
|
|
||||||
final playlists = db.getPlaylists(users[0].id);
|
|
||||||
if (playlists.isNotEmpty) playlist = playlists.first;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (playlist != null) {
|
final user = request.context['user'] as User?;
|
||||||
return PlaylistConfig(
|
if (user != null) {
|
||||||
id: playlist.id,
|
final playlists = db.getPlaylists(user.id);
|
||||||
name: playlist.name,
|
if (playlists.isNotEmpty) playlist = playlists.first;
|
||||||
dns: playlist.serverUrl,
|
} else {
|
||||||
username: playlist.username,
|
// Fallback: Try to find a playlist for any user if no specific user is logged in
|
||||||
password: playlist.password,
|
final users = db.getAllUsers();
|
||||||
createdAt: playlist.createdAt,
|
if (users.isNotEmpty) {
|
||||||
isActive: true,
|
final playlists = db.getPlaylists(users[0].id);
|
||||||
);
|
if (playlists.isNotEmpty) playlist = playlists.first;
|
||||||
}
|
}
|
||||||
return null;
|
}
|
||||||
|
|
||||||
|
if (playlist != null) {
|
||||||
|
return PlaylistConfig(
|
||||||
|
id: playlist.id,
|
||||||
|
name: playlist.name,
|
||||||
|
dns: playlist.serverUrl,
|
||||||
|
username: playlist.username,
|
||||||
|
password: playlist.password,
|
||||||
|
createdAt: playlist.createdAt,
|
||||||
|
isActive: true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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(
|
||||||
@@ -186,7 +203,7 @@ void main(List<String> args) async {
|
|||||||
print('Serving static files from: $webPath');
|
print('Serving static files from: $webPath');
|
||||||
print('REST API available at: /api/auth/* and /api/playlists/*');
|
print('REST API available at: /api/auth/* and /api/playlists/*');
|
||||||
print('Xtream proxy available at: /api/xtream/*');
|
print('Xtream proxy available at: /api/xtream/*');
|
||||||
|
|
||||||
// Clean expired sessions periodically (every hour)
|
// Clean expired sessions periodically (every hour)
|
||||||
Timer.periodic(const Duration(hours: 1), (_) {
|
Timer.periodic(const Duration(hours: 1), (_) {
|
||||||
db.cleanExpiredSessions();
|
db.cleanExpiredSessions();
|
||||||
@@ -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) {
|
||||||
@@ -232,12 +247,12 @@ Handler _createXtreamProxyHandler() {
|
|||||||
// Extract target URL from request
|
// Extract target URL from request
|
||||||
// Format: /api/xtream/http://server:port/path
|
// Format: /api/xtream/http://server:port/path
|
||||||
String apiPath = path.substring('api/xtream/'.length);
|
String apiPath = path.substring('api/xtream/'.length);
|
||||||
|
|
||||||
// Decode URL if it's encoded
|
// Decode URL if it's encoded
|
||||||
if (apiPath.startsWith('http%3A') || apiPath.startsWith('https%3A')) {
|
if (apiPath.startsWith('http%3A') || apiPath.startsWith('https%3A')) {
|
||||||
apiPath = Uri.decodeComponent(apiPath);
|
apiPath = Uri.decodeComponent(apiPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!apiPath.startsWith('http://') && !apiPath.startsWith('https://')) {
|
if (!apiPath.startsWith('http://') && !apiPath.startsWith('https://')) {
|
||||||
return Response.badRequest(
|
return Response.badRequest(
|
||||||
body: 'Invalid API URL. Expected format: /api/xtream/http://...',
|
body: 'Invalid API URL. Expected format: /api/xtream/http://...',
|
||||||
@@ -252,7 +267,7 @@ Handler _createXtreamProxyHandler() {
|
|||||||
fullUrl = '$fullUrl?${request.url.query}';
|
fullUrl = '$fullUrl?${request.url.query}';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final targetUrl = Uri.parse(fullUrl);
|
final targetUrl = Uri.parse(fullUrl);
|
||||||
|
|
||||||
final proxyHeaders = {
|
final proxyHeaders = {
|
||||||
@@ -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': '*',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in new issue
Block a user