mirror of
https://github.com/R0m1k3/xtremflow.git
synced 2026-10-22 14:38:06 +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
+115
-97
@@ -10,7 +10,7 @@ import 'package:args/args.dart';
|
||||
import 'database/database.dart';
|
||||
import 'models/user.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/users_handler.dart';
|
||||
import 'api/playlists_handler.dart';
|
||||
@@ -25,7 +25,7 @@ void main(List<String> args) async {
|
||||
final parser = ArgParser()
|
||||
..addOption('port', abbr: 'p', defaultsTo: '8089')
|
||||
..addOption('path', defaultsTo: '/app/web');
|
||||
|
||||
|
||||
final result = parser.parse(args);
|
||||
final port = int.parse(result['port']);
|
||||
final webPath = result['path'];
|
||||
@@ -49,48 +49,61 @@ void main(List<String> args) async {
|
||||
// Auth endpoints
|
||||
..mount('/api/auth', authHandler.router)
|
||||
// Playlists endpoints
|
||||
..mount('/api/playlists', const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler(playlistsHandler.router.call),)
|
||||
..mount(
|
||||
'/api/playlists',
|
||||
const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler(playlistsHandler.router.call),
|
||||
)
|
||||
// Users endpoints
|
||||
..mount('/api/users', const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler(usersHandler.router.call),)
|
||||
..mount(
|
||||
'/api/users',
|
||||
const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler(usersHandler.router.call),
|
||||
)
|
||||
// Settings endpoints
|
||||
..mount('/api/settings', const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler(settingsHandler.router.call),);
|
||||
..mount(
|
||||
'/api/settings',
|
||||
const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler(settingsHandler.router.call),
|
||||
);
|
||||
|
||||
// Initialize Cleanup Service
|
||||
final cleanupService = CleanupService();
|
||||
cleanupService.addTarget(Directory.systemTemp);
|
||||
cleanupService.addTarget(Directory('/app/data/logs'));
|
||||
cleanupService.addTarget(Directory('/app/data/tmp'));
|
||||
|
||||
|
||||
cleanupService.start();
|
||||
|
||||
// Admin Routes (protected)
|
||||
apiRouter.mount('/api/admin', const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler((Request request) {
|
||||
final router = Router();
|
||||
|
||||
// POST /api/admin/purge
|
||||
router.post('/purge', (Request req) async {
|
||||
final user = req.context['user'] as User?;
|
||||
if (user == null || !user.isAdmin) {
|
||||
return Response.forbidden(jsonEncode({'error': 'Admin access required'}));
|
||||
}
|
||||
|
||||
final result = await cleanupService.runCleanup();
|
||||
return Response.ok(
|
||||
jsonEncode(result),
|
||||
headers: {'content-type': 'application/json'},
|
||||
);
|
||||
});
|
||||
|
||||
return router(request);
|
||||
}),);
|
||||
apiRouter.mount(
|
||||
'/api/admin',
|
||||
const Pipeline()
|
||||
.addMiddleware(authMiddleware(db))
|
||||
.addHandler((Request request) {
|
||||
final router = Router();
|
||||
|
||||
// POST /api/admin/purge
|
||||
router.post('/purge', (Request req) async {
|
||||
final user = req.context['user'] as User?;
|
||||
if (user == null || !user.isAdmin) {
|
||||
return Response.forbidden(
|
||||
jsonEncode({'error': 'Admin access required'}));
|
||||
}
|
||||
|
||||
final result = await cleanupService.runCleanup();
|
||||
return Response.ok(
|
||||
jsonEncode(result),
|
||||
headers: {'content-type': 'application/json'},
|
||||
);
|
||||
});
|
||||
|
||||
return router(request);
|
||||
}),
|
||||
);
|
||||
|
||||
// Create static handler
|
||||
final baseStaticHandler = createStaticHandler(
|
||||
@@ -102,55 +115,59 @@ void main(List<String> args) async {
|
||||
// Wrap static handler to enforce cache policies
|
||||
FutureOr<Response> staticHandler(Request request) async {
|
||||
final response = await baseStaticHandler(request);
|
||||
|
||||
|
||||
// Disable cache for entry points to ensure updates are seen immediately
|
||||
final path = request.url.path;
|
||||
if (path.isEmpty ||
|
||||
path == 'index.html' ||
|
||||
path.endsWith('.js') ||
|
||||
if (path.isEmpty ||
|
||||
path == 'index.html' ||
|
||||
path.endsWith('.js') ||
|
||||
path.endsWith('.json')) {
|
||||
return response.change(headers: {
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
|
||||
'Pragma': 'no-cache',
|
||||
'Expires': '0',
|
||||
},);
|
||||
return response.change(
|
||||
headers: {
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
|
||||
'Pragma': 'no-cache',
|
||||
'Expires': '0',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Allow aggressive caching for hashed assets
|
||||
return response.change(headers: {
|
||||
'Cache-Control': 'public, max-age=86400',
|
||||
},);
|
||||
return response.change(
|
||||
headers: {
|
||||
'Cache-Control': 'public, max-age=86400',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Helper to get playlist from request
|
||||
Future<PlaylistConfig?> getPlaylist(Request request) async {
|
||||
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;
|
||||
}
|
||||
}
|
||||
Playlist? playlist;
|
||||
|
||||
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;
|
||||
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) {
|
||||
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)
|
||||
@@ -160,20 +177,20 @@ void main(List<String> args) async {
|
||||
|
||||
// Main handler with API proxy and NEW Streaming Handlers
|
||||
final handler = Cascade()
|
||||
.add(apiRouter.call) /* Standard API endpoints */
|
||||
.add(_createXtreamProxyHandler()) /* Keep for general API calls */
|
||||
.add(streamingRouter.call) /* Streaming endpoints */
|
||||
.add(staticHandler)
|
||||
.handler;
|
||||
.add(apiRouter.call) /* Standard API endpoints */
|
||||
.add(_createXtreamProxyHandler()) /* Keep for general API calls */
|
||||
.add(streamingRouter.call) /* Streaming endpoints */
|
||||
.add(staticHandler)
|
||||
.handler;
|
||||
|
||||
// Add middleware
|
||||
final pipeline = const Pipeline()
|
||||
.addMiddleware(logRequests())
|
||||
.addMiddleware(securityHeadersMiddleware())
|
||||
.addMiddleware(honeypotMiddleware())
|
||||
.addMiddleware(rateLimitMiddleware())
|
||||
.addMiddleware(_corsMiddleware())
|
||||
.addHandler(handler);
|
||||
.addMiddleware(logRequests())
|
||||
.addMiddleware(securityHeadersMiddleware())
|
||||
.addMiddleware(honeypotMiddleware())
|
||||
.addMiddleware(rateLimitMiddleware())
|
||||
.addMiddleware(_corsMiddleware())
|
||||
.addHandler(handler);
|
||||
|
||||
// Start server
|
||||
final server = await shelf_io.serve(
|
||||
@@ -186,7 +203,7 @@ void main(List<String> args) async {
|
||||
print('Serving static files from: $webPath');
|
||||
print('REST API available at: /api/auth/* and /api/playlists/*');
|
||||
print('Xtream proxy available at: /api/xtream/*');
|
||||
|
||||
|
||||
// Clean expired sessions periodically (every hour)
|
||||
Timer.periodic(const Duration(hours: 1), (_) {
|
||||
db.cleanExpiredSessions();
|
||||
@@ -194,8 +211,6 @@ void main(List<String> args) async {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// CORS middleware to allow cross-origin requests
|
||||
Middleware _corsMiddleware() {
|
||||
return (Handler handler) {
|
||||
@@ -232,12 +247,12 @@ Handler _createXtreamProxyHandler() {
|
||||
// Extract target URL from request
|
||||
// Format: /api/xtream/http://server:port/path
|
||||
String apiPath = path.substring('api/xtream/'.length);
|
||||
|
||||
|
||||
// Decode URL if it's encoded
|
||||
if (apiPath.startsWith('http%3A') || apiPath.startsWith('https%3A')) {
|
||||
apiPath = Uri.decodeComponent(apiPath);
|
||||
}
|
||||
|
||||
|
||||
if (!apiPath.startsWith('http://') && !apiPath.startsWith('https://')) {
|
||||
return Response.badRequest(
|
||||
body: 'Invalid API URL. Expected format: /api/xtream/http://...',
|
||||
@@ -252,7 +267,7 @@ Handler _createXtreamProxyHandler() {
|
||||
fullUrl = '$fullUrl?${request.url.query}';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
final targetUrl = Uri.parse(fullUrl);
|
||||
|
||||
final proxyHeaders = {
|
||||
@@ -265,15 +280,17 @@ Handler _createXtreamProxyHandler() {
|
||||
http.Response response;
|
||||
if (request.method == 'GET') {
|
||||
response = await http.get(targetUrl, headers: proxyHeaders).timeout(
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () => http.Response('Request timeout', 504),
|
||||
);
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () => http.Response('Request timeout', 504),
|
||||
);
|
||||
} else if (request.method == 'POST') {
|
||||
final body = await request.readAsString();
|
||||
response = await http.post(targetUrl, headers: proxyHeaders, body: body).timeout(
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () => http.Response('Request timeout', 504),
|
||||
);
|
||||
response = await http
|
||||
.post(targetUrl, headers: proxyHeaders, body: body)
|
||||
.timeout(
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () => http.Response('Request timeout', 504),
|
||||
);
|
||||
} else {
|
||||
return Response(405, body: 'Method not allowed');
|
||||
}
|
||||
@@ -282,7 +299,8 @@ Handler _createXtreamProxyHandler() {
|
||||
response.statusCode,
|
||||
body: response.bodyBytes,
|
||||
headers: {
|
||||
'content-type': response.headers['content-type'] ?? 'application/json',
|
||||
'content-type':
|
||||
response.headers['content-type'] ?? 'application/json',
|
||||
'access-control-allow-origin': '*',
|
||||
},
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user