Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44a1674c28 | ||
|
|
91494f7d25 |
@@ -31,8 +31,8 @@ jobs:
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.38.0'
|
||||
channel: 'master'
|
||||
flutter-version: '3.24.0'
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
|
||||
- name: Cache Gradle dependencies
|
||||
@@ -63,7 +63,10 @@ jobs:
|
||||
|
||||
- name: Setup signing keystore
|
||||
run: |
|
||||
# Decode keystore from secret (persistent key for consistent signatures)
|
||||
echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 -d > android/app/upload-keystore.jks
|
||||
|
||||
# Create key.properties file
|
||||
cat > android/key.properties << EOF
|
||||
storePassword=${{ secrets.KEYSTORE_PASSWORD }}
|
||||
keyPassword=${{ secrets.KEY_PASSWORD }}
|
||||
@@ -72,7 +75,12 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Build APK
|
||||
run: flutter build apk --release
|
||||
run: |
|
||||
# Use init.gradle to force Maven mirrors (workaround for Maven Central 403)
|
||||
mkdir -p ~/.gradle
|
||||
cp android/init.gradle ~/.gradle/init.gradle
|
||||
|
||||
flutter build apk --release
|
||||
|
||||
- name: Upload APK artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -83,5 +91,10 @@ jobs:
|
||||
|
||||
- name: Upload APK summary
|
||||
run: |
|
||||
echo "## APK Build Successful!" >> $GITHUB_STEP_SUMMARY
|
||||
echo "## APK Build Successful! 🎉" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "📱 **APK Location:** \`build/app/outputs/flutter-apk/app-release.apk\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "📦 **Download:** Check the artifacts section below" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
ls -lh build/app/outputs/flutter-apk/app-release.apk >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -30,16 +30,16 @@ if (keystorePropertiesFile.exists()) {
|
||||
|
||||
android {
|
||||
namespace "com.musicassistant.music_assistant"
|
||||
compileSdk 35
|
||||
compileSdk 36
|
||||
ndkVersion flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
jvmTarget = '17'
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
|
||||
@@ -1653,55 +1653,5 @@
|
||||
"selectPlayerToAddToQueue": "Select player to add to queue",
|
||||
"@selectPlayerToAddToQueue": {
|
||||
"description": "Hint for selecting player to add to queue"
|
||||
},
|
||||
|
||||
"localConnection": "Server URL",
|
||||
"@localConnection": {
|
||||
"description": "Direct connection mode toggle label"
|
||||
},
|
||||
|
||||
"remoteConnection": "Remote Access ID",
|
||||
"@remoteConnection": {
|
||||
"description": "HA Remote Access connection mode toggle label"
|
||||
},
|
||||
|
||||
"remoteAccessId": "Remote Access ID",
|
||||
"@remoteAccessId": {
|
||||
"description": "Remote access ID field label"
|
||||
},
|
||||
|
||||
"remoteAccessIdHint": "Find this in Music Assistant Settings → Remote Access",
|
||||
"@remoteAccessIdHint": {
|
||||
"description": "Hint for remote access ID field"
|
||||
},
|
||||
|
||||
"remoteAccessNote": "For Home Assistant add-on users only",
|
||||
"@remoteAccessNote": {
|
||||
"description": "Note about remote access availability"
|
||||
},
|
||||
|
||||
"pleaseEnterRemoteId": "Please enter your Remote Access ID",
|
||||
"@pleaseEnterRemoteId": {
|
||||
"description": "Validation message for remote access ID"
|
||||
},
|
||||
|
||||
"remoteConnectionFailed": "Remote connection failed. Please check your Remote Access ID and credentials.",
|
||||
"@remoteConnectionFailed": {
|
||||
"description": "Error message when remote connection fails"
|
||||
},
|
||||
|
||||
"scanQrCode": "Scan QR Code",
|
||||
"@scanQrCode": {
|
||||
"description": "Title for QR code scanner screen"
|
||||
},
|
||||
|
||||
"pointCameraAtQr": "Point your camera at the Remote Access QR code in Music Assistant settings",
|
||||
"@pointCameraAtQr": {
|
||||
"description": "Instructions for scanning QR code"
|
||||
},
|
||||
|
||||
"cameraPermissionDenied": "Camera permission is required to scan QR codes",
|
||||
"@cameraPermissionDenied": {
|
||||
"description": "Error message when camera permission is denied"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2122,66 +2122,6 @@ abstract class S {
|
||||
/// In en, this message translates to:
|
||||
/// **'Select player to add to queue'**
|
||||
String get selectPlayerToAddToQueue;
|
||||
|
||||
/// Direct connection mode toggle label
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Server URL'**
|
||||
String get localConnection;
|
||||
|
||||
/// HA Remote Access connection mode toggle label
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Remote Access ID'**
|
||||
String get remoteConnection;
|
||||
|
||||
/// Remote access ID field label
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Remote Access ID'**
|
||||
String get remoteAccessId;
|
||||
|
||||
/// Hint for remote access ID field
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Find this in Music Assistant Settings → Remote Access'**
|
||||
String get remoteAccessIdHint;
|
||||
|
||||
/// Note about remote access availability
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'For Home Assistant add-on users only'**
|
||||
String get remoteAccessNote;
|
||||
|
||||
/// Validation message for remote access ID
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Please enter your Remote Access ID'**
|
||||
String get pleaseEnterRemoteId;
|
||||
|
||||
/// Error message when remote connection fails
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Remote connection failed. Please check your Remote Access ID and credentials.'**
|
||||
String get remoteConnectionFailed;
|
||||
|
||||
/// Title for QR code scanner screen
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Scan QR Code'**
|
||||
String get scanQrCode;
|
||||
|
||||
/// Instructions for scanning QR code
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Point your camera at the Remote Access QR code in Music Assistant settings'**
|
||||
String get pointCameraAtQr;
|
||||
|
||||
/// Error message when camera permission is denied
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Camera permission is required to scan QR codes'**
|
||||
String get cameraPermissionDenied;
|
||||
}
|
||||
|
||||
class _SDelegate extends LocalizationsDelegate<S> {
|
||||
|
||||
@@ -1155,38 +1155,4 @@ class SDe extends S {
|
||||
|
||||
@override
|
||||
String get selectPlayerToAddToQueue => 'Select player to add to queue';
|
||||
|
||||
@override
|
||||
String get localConnection => 'Server URL';
|
||||
|
||||
@override
|
||||
String get remoteConnection => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessId => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessIdHint =>
|
||||
'Find this in Music Assistant Settings → Remote Access';
|
||||
|
||||
@override
|
||||
String get remoteAccessNote => 'For Home Assistant add-on users only';
|
||||
|
||||
@override
|
||||
String get pleaseEnterRemoteId => 'Please enter your Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteConnectionFailed =>
|
||||
'Remote connection failed. Please check your Remote Access ID and credentials.';
|
||||
|
||||
@override
|
||||
String get scanQrCode => 'Scan QR Code';
|
||||
|
||||
@override
|
||||
String get pointCameraAtQr =>
|
||||
'Point your camera at the Remote Access QR code in Music Assistant settings';
|
||||
|
||||
@override
|
||||
String get cameraPermissionDenied =>
|
||||
'Camera permission is required to scan QR codes';
|
||||
}
|
||||
|
||||
@@ -1147,38 +1147,4 @@ class SEn extends S {
|
||||
|
||||
@override
|
||||
String get selectPlayerToAddToQueue => 'Select player to add to queue';
|
||||
|
||||
@override
|
||||
String get localConnection => 'Server URL';
|
||||
|
||||
@override
|
||||
String get remoteConnection => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessId => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessIdHint =>
|
||||
'Find this in Music Assistant Settings → Remote Access';
|
||||
|
||||
@override
|
||||
String get remoteAccessNote => 'For Home Assistant add-on users only';
|
||||
|
||||
@override
|
||||
String get pleaseEnterRemoteId => 'Please enter your Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteConnectionFailed =>
|
||||
'Remote connection failed. Please check your Remote Access ID and credentials.';
|
||||
|
||||
@override
|
||||
String get scanQrCode => 'Scan QR Code';
|
||||
|
||||
@override
|
||||
String get pointCameraAtQr =>
|
||||
'Point your camera at the Remote Access QR code in Music Assistant settings';
|
||||
|
||||
@override
|
||||
String get cameraPermissionDenied =>
|
||||
'Camera permission is required to scan QR codes';
|
||||
}
|
||||
|
||||
@@ -1163,38 +1163,4 @@ class SEs extends S {
|
||||
|
||||
@override
|
||||
String get selectPlayerToAddToQueue => 'Select player to add to queue';
|
||||
|
||||
@override
|
||||
String get localConnection => 'Server URL';
|
||||
|
||||
@override
|
||||
String get remoteConnection => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessId => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessIdHint =>
|
||||
'Find this in Music Assistant Settings → Remote Access';
|
||||
|
||||
@override
|
||||
String get remoteAccessNote => 'For Home Assistant add-on users only';
|
||||
|
||||
@override
|
||||
String get pleaseEnterRemoteId => 'Please enter your Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteConnectionFailed =>
|
||||
'Remote connection failed. Please check your Remote Access ID and credentials.';
|
||||
|
||||
@override
|
||||
String get scanQrCode => 'Scan QR Code';
|
||||
|
||||
@override
|
||||
String get pointCameraAtQr =>
|
||||
'Point your camera at the Remote Access QR code in Music Assistant settings';
|
||||
|
||||
@override
|
||||
String get cameraPermissionDenied =>
|
||||
'Camera permission is required to scan QR codes';
|
||||
}
|
||||
|
||||
@@ -1172,38 +1172,4 @@ class SFr extends S {
|
||||
|
||||
@override
|
||||
String get selectPlayerToAddToQueue => 'Select player to add to queue';
|
||||
|
||||
@override
|
||||
String get localConnection => 'Server URL';
|
||||
|
||||
@override
|
||||
String get remoteConnection => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessId => 'Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteAccessIdHint =>
|
||||
'Find this in Music Assistant Settings → Remote Access';
|
||||
|
||||
@override
|
||||
String get remoteAccessNote => 'For Home Assistant add-on users only';
|
||||
|
||||
@override
|
||||
String get pleaseEnterRemoteId => 'Please enter your Remote Access ID';
|
||||
|
||||
@override
|
||||
String get remoteConnectionFailed =>
|
||||
'Remote connection failed. Please check your Remote Access ID and credentials.';
|
||||
|
||||
@override
|
||||
String get scanQrCode => 'Scan QR Code';
|
||||
|
||||
@override
|
||||
String get pointCameraAtQr =>
|
||||
'Point your camera at the Remote Access QR code in Music Assistant settings';
|
||||
|
||||
@override
|
||||
String get cameraPermissionDenied =>
|
||||
'Camera permission is required to scan QR codes';
|
||||
}
|
||||
|
||||
+1
-25
@@ -330,31 +330,7 @@ class _MusicAssistantAppState extends State<MusicAssistantApp> with WidgetsBindi
|
||||
darkTheme: AppTheme.darkTheme(colorScheme: darkColorScheme),
|
||||
builder: (context, child) {
|
||||
// Wrap entire app with global player overlay
|
||||
// Also include hidden WebView for remote WebRTC bridge
|
||||
final musicProvider = context.read<MusicAssistantProvider>();
|
||||
return Stack(
|
||||
children: [
|
||||
GlobalPlayerOverlay(child: child ?? const SizedBox.shrink()),
|
||||
// WebView for WebRTC - must be VISIBLE to avoid Android throttling
|
||||
// A tiny 4x4 pixel dot at bottom-right, nearly invisible but keeps WebView active
|
||||
Positioned(
|
||||
right: 4,
|
||||
bottom: 4,
|
||||
child: Container(
|
||||
width: 4,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withOpacity(0.1), // Nearly invisible dot
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
child: musicProvider.remoteBridgeWebView,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
return GlobalPlayerOverlay(child: child ?? const SizedBox.shrink());
|
||||
},
|
||||
home: const AppStartup(),
|
||||
),
|
||||
|
||||
@@ -31,20 +31,14 @@ class ProviderMapping {
|
||||
});
|
||||
|
||||
factory ProviderMapping.fromJson(Map<String, dynamic> json) {
|
||||
// Parse in_library field - MA uses 1/0 or true/false
|
||||
// Default to true if not present (items from library_items API are in library)
|
||||
final inLibraryValue = json['in_library'];
|
||||
final inLibrary = inLibraryValue == null
|
||||
? true // Default: items fetched from library are in library
|
||||
: inLibraryValue == true || inLibraryValue == 1;
|
||||
|
||||
return ProviderMapping(
|
||||
itemId: json['item_id'] as String? ?? '',
|
||||
providerDomain: json['provider_domain'] as String? ?? '',
|
||||
providerInstance: json['provider_instance'] as String? ?? '',
|
||||
available: json['available'] as bool? ?? true,
|
||||
audioFormat: json['audio_format'] as Map<String, dynamic>?,
|
||||
inLibrary: inLibrary,
|
||||
// Parse in_library field - MA uses 1/0 or true/false
|
||||
inLibrary: json['in_library'] == true || json['in_library'] == 1,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/painting.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:audio_service/audio_service.dart' as audio_service;
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter_volume_controller/flutter_volume_controller.dart';
|
||||
@@ -107,19 +106,9 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
SendspinService? _sendspinService;
|
||||
bool _sendspinConnected = false;
|
||||
|
||||
// Remote mode flag - persisted across reconnections
|
||||
bool _isRemoteMode = false;
|
||||
|
||||
// Remote cloud URL for Sendspin connection (e.g., xxxxxxxx.ui.nabu.casa)
|
||||
String? _remoteCloudUrl;
|
||||
|
||||
// Remote bridge for WebRTC tunnel (kept alive for reconnection)
|
||||
// Created early so WebView can be added to widget tree before start()
|
||||
final RemoteBridge _remoteBridge = RemoteBridge();
|
||||
StreamSubscription<RemoteBridgeState>? _remoteBridgeStateSubscription;
|
||||
|
||||
// Remote mode auto-reconnect timer (retries every 30s when disconnected)
|
||||
Timer? _remoteReconnectTimer;
|
||||
// Remote connection (WebRTC-to-WS bridge for remote access)
|
||||
RemoteBridge? _remoteBridge;
|
||||
bool get isRemoteConnection => _remoteBridge != null && _remoteBridge!.isRunning;
|
||||
|
||||
// PCM audio player for raw Sendspin audio streaming
|
||||
PcmAudioPlayer? _pcmAudioPlayer;
|
||||
@@ -161,10 +150,6 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
bool get isConnected => _connectionState == MAConnectionState.connected ||
|
||||
_connectionState == MAConnectionState.authenticated;
|
||||
|
||||
/// Get the hidden WebView widget for remote bridge WebRTC.
|
||||
/// This MUST be added to the widget tree for remote connections to work.
|
||||
Widget get remoteBridgeWebView => _remoteBridge.buildWebView();
|
||||
|
||||
// Library getters with provider filtering applied
|
||||
List<Artist> get artists => filterByProvider(_artists);
|
||||
List<Album> get albums => filterByProvider(_albums);
|
||||
@@ -840,102 +825,11 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
if (_serverUrl != null && _serverUrl!.isNotEmpty) {
|
||||
await _restoreAuthCredentials();
|
||||
|
||||
// Check if this is a localhost bridge URL that needs remote reconnection
|
||||
final remoteAccessId = await SettingsService.getRemoteAccessId();
|
||||
final isLocalhostUrl = _serverUrl!.contains('localhost') || _serverUrl!.contains('127.0.0.1');
|
||||
|
||||
if (isLocalhostUrl && remoteAccessId != null && remoteAccessId.isNotEmpty) {
|
||||
// This is a remote connection - need to re-establish bridge
|
||||
_logger.log('🌐 Detected remote mode, re-establishing bridge for: $remoteAccessId');
|
||||
await _reconnectViaRemoteBridge(remoteAccessId);
|
||||
} else {
|
||||
// Direct/local connection
|
||||
await connectToServer(_serverUrl!);
|
||||
}
|
||||
|
||||
await connectToServer(_serverUrl!);
|
||||
await _initializeLocalPlayback();
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-establish remote bridge connection on app restart
|
||||
Future<void> _reconnectViaRemoteBridge(String remoteAccessId) async {
|
||||
final username = await SettingsService.getUsername();
|
||||
final password = await SettingsService.getPassword();
|
||||
|
||||
if (username == null || password == null) {
|
||||
_logger.log('❌ Remote reconnect failed: no credentials saved');
|
||||
// Clear remote access ID since we can't reconnect
|
||||
await SettingsService.clearRemoteAccessId();
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.log('🔄 Starting remote bridge for reconnection...');
|
||||
|
||||
try {
|
||||
// Use existing bridge instance (WebView is already in widget tree)
|
||||
// Subscribe to bridge state changes for auto-reconnect
|
||||
_remoteBridgeStateSubscription?.cancel();
|
||||
_remoteBridgeStateSubscription = _remoteBridge.stateStream.listen((state) {
|
||||
_logger.log('🔄 RemoteBridge state: $state (API state: $_connectionState)');
|
||||
if (state == RemoteBridgeState.connected &&
|
||||
(_connectionState == MAConnectionState.disconnected ||
|
||||
_connectionState == MAConnectionState.error)) {
|
||||
// Bridge reconnected but API is disconnected - reconnect API immediately
|
||||
_logger.log('🔄 Bridge reconnected, triggering immediate API reconnect');
|
||||
_reconnectApiToBridge();
|
||||
}
|
||||
});
|
||||
|
||||
final port = await _remoteBridge.start(remoteAccessId, username, password);
|
||||
|
||||
if (port == null) {
|
||||
_logger.log('❌ Remote bridge failed to start');
|
||||
// Clear remote access ID since bridge failed
|
||||
await SettingsService.clearRemoteAccessId();
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.log('✅ Remote bridge started on port $port');
|
||||
|
||||
// Update server URL to the new bridge port
|
||||
final bridgeUrl = 'ws://localhost:$port';
|
||||
await SettingsService.setServerUrl(bridgeUrl);
|
||||
|
||||
// Connect through the bridge
|
||||
await connectToServer(bridgeUrl, isRemoteMode: true, remoteCloudUrl: remoteAccessId);
|
||||
} catch (e) {
|
||||
_logger.log('❌ Remote reconnect error: $e');
|
||||
await SettingsService.clearRemoteAccessId();
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the remote bridge for initial connection (called from LoginScreen).
|
||||
/// Returns the local port number to connect to, or null if failed.
|
||||
Future<int?> startRemoteBridge(String remoteId, String username, String password) async {
|
||||
_logger.log('🔄 Starting remote bridge for: $remoteId');
|
||||
|
||||
try {
|
||||
// Subscribe to bridge state changes for auto-reconnect
|
||||
_remoteBridgeStateSubscription?.cancel();
|
||||
_remoteBridgeStateSubscription = _remoteBridge.stateStream.listen((state) {
|
||||
_logger.log('🔄 RemoteBridge state: $state (API state: $_connectionState)');
|
||||
if (state == RemoteBridgeState.connected &&
|
||||
(_connectionState == MAConnectionState.disconnected ||
|
||||
_connectionState == MAConnectionState.error)) {
|
||||
_logger.log('🔄 Bridge reconnected, triggering immediate API reconnect');
|
||||
_reconnectApiToBridge();
|
||||
}
|
||||
});
|
||||
|
||||
final port = await _remoteBridge.start(remoteId, username, password);
|
||||
return port;
|
||||
} catch (e) {
|
||||
_logger.log('❌ Remote bridge start error: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Load cached players from database for instant UI display
|
||||
Future<void> _loadPlayersFromDatabase() async {
|
||||
try {
|
||||
@@ -1140,19 +1034,16 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// CONNECTION
|
||||
// ============================================================================
|
||||
|
||||
Future<void> connectToServer(String serverUrl, {bool isRemoteMode = false, String? remoteCloudUrl}) async {
|
||||
Future<void> connectToServer(String serverUrl) async {
|
||||
try {
|
||||
_error = null;
|
||||
_serverUrl = serverUrl;
|
||||
_isRemoteMode = isRemoteMode; // Store for reconnection
|
||||
_remoteCloudUrl = remoteCloudUrl; // Store cloud URL for Sendspin in remote mode
|
||||
await SettingsService.setServerUrl(serverUrl);
|
||||
|
||||
// Dispose the old API to stop any pending reconnects
|
||||
_api?.dispose();
|
||||
|
||||
_api = MusicAssistantAPI(serverUrl, _authManager);
|
||||
_api!.isRemoteMode = isRemoteMode;
|
||||
|
||||
_connectionStateSubscription?.cancel();
|
||||
_connectionStateSubscription = _api!.connectionState.listen(
|
||||
@@ -1177,11 +1068,9 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
// No auth required, initialize immediately
|
||||
_stopRemoteReconnectTimer(); // Stop retry timer on successful connection
|
||||
await _initializeAfterConnection();
|
||||
} else if (state == MAConnectionState.authenticated) {
|
||||
_logger.log('✅ MA authentication successful');
|
||||
_stopRemoteReconnectTimer(); // Stop retry timer on successful connection
|
||||
// Now safe to initialize since we're authenticated
|
||||
await _initializeAfterConnection();
|
||||
} else if (state == MAConnectionState.disconnected) {
|
||||
@@ -1189,14 +1078,11 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// Keep showing cached data for instant UI display on reconnect
|
||||
// Player list and state will be refreshed when connection is restored
|
||||
_logger.log('📡 Disconnected - keeping cached players and data for instant resume');
|
||||
// Start reconnect timer in remote mode
|
||||
_startRemoteReconnectTimer();
|
||||
}
|
||||
},
|
||||
onError: (error) {
|
||||
_logger.log('Connection state stream error: $error');
|
||||
_connectionState = MAConnectionState.error;
|
||||
_startRemoteReconnectTimer(); // Start retry timer in remote mode
|
||||
notifyListeners();
|
||||
},
|
||||
);
|
||||
@@ -1244,6 +1130,61 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to a remote MA server via WebRTC using Remote Access ID.
|
||||
/// Uses a WebRTC-to-WebSocket bridge so MusicAssistantAPI works unchanged.
|
||||
Future<bool> connectRemote(String remoteId, String username, String password) async {
|
||||
_logger.log('🌐 Attempting remote connection to: $remoteId');
|
||||
|
||||
try {
|
||||
_error = null;
|
||||
_connectionState = MAConnectionState.connecting;
|
||||
notifyListeners();
|
||||
|
||||
// Start the WebRTC-to-WS bridge
|
||||
_remoteBridge = RemoteBridge();
|
||||
final port = await _remoteBridge!.start(remoteId, username, password);
|
||||
|
||||
if (port == null) {
|
||||
_logger.log('❌ Remote bridge failed to start');
|
||||
_remoteBridge = null;
|
||||
_connectionState = MAConnectionState.error;
|
||||
_error = 'Remote connection failed';
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.log('✅ Remote bridge started on port $port');
|
||||
|
||||
// Connect via normal API - it will hit the local bridge
|
||||
// The bridge already authenticated, so we use the same credentials
|
||||
await SettingsService.setUsername(username);
|
||||
await SettingsService.setPassword(password);
|
||||
|
||||
await connectToServer('ws://localhost:$port');
|
||||
|
||||
// Wait a moment for connection to establish
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
if (isConnected) {
|
||||
_logger.log('✅ Remote connection via bridge successful!');
|
||||
return true;
|
||||
} else {
|
||||
_logger.log('❌ Connection to bridge failed, stopping bridge');
|
||||
await _remoteBridge?.stop();
|
||||
_remoteBridge = null;
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('❌ Remote connection error: $e');
|
||||
await _remoteBridge?.stop();
|
||||
_remoteBridge = null;
|
||||
_error = e.toString();
|
||||
_connectionState = MAConnectionState.error;
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _handleMaAuthentication() async {
|
||||
if (_api == null) return false;
|
||||
|
||||
@@ -1935,6 +1876,11 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
_sendspinConnected = false;
|
||||
}
|
||||
await _api?.disconnect();
|
||||
// Stop remote bridge if running
|
||||
if (_remoteBridge != null) {
|
||||
await _remoteBridge!.stop();
|
||||
_remoteBridge = null;
|
||||
}
|
||||
_connectionState = MAConnectionState.disconnected;
|
||||
// DON'T clear caches or player state - keep for instant reconnect
|
||||
_logger.log('📡 Explicit disconnect - keeping cached data for instant resume');
|
||||
@@ -1994,28 +1940,13 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
if (_connectionState != MAConnectionState.connected &&
|
||||
_connectionState != MAConnectionState.authenticated) {
|
||||
_logger.log('🔄 Not connected, attempting reconnect to $_serverUrl (remote: $_isRemoteMode)');
|
||||
|
||||
// In remote mode, retry multiple times since bridge may be recovering
|
||||
final maxRetries = _isRemoteMode ? 5 : 1;
|
||||
for (var attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
await connectToServer(_serverUrl!, isRemoteMode: _isRemoteMode, remoteCloudUrl: _remoteCloudUrl);
|
||||
_logger.log('🔄 Reconnection successful on attempt $attempt');
|
||||
return;
|
||||
} catch (e) {
|
||||
_logger.log('🔄 Reconnection attempt $attempt/$maxRetries failed: $e');
|
||||
if (attempt < maxRetries) {
|
||||
// Exponential backoff: 2s, 4s, 8s, 16s
|
||||
final delay = Duration(seconds: 2 << (attempt - 1));
|
||||
_logger.log('🔄 Retrying in ${delay.inSeconds}s...');
|
||||
await Future.delayed(delay);
|
||||
}
|
||||
}
|
||||
_logger.log('🔄 Not connected, attempting reconnect to $_serverUrl');
|
||||
try {
|
||||
await connectToServer(_serverUrl!);
|
||||
_logger.log('🔄 Reconnection successful');
|
||||
} catch (e) {
|
||||
_logger.log('🔄 Reconnection failed: $e');
|
||||
}
|
||||
_logger.log('🔄 All reconnection attempts failed');
|
||||
// Start periodic reconnect timer for remote mode
|
||||
_startRemoteReconnectTimer();
|
||||
} else {
|
||||
_logger.log('🔄 Already connected, verifying connection...');
|
||||
try {
|
||||
@@ -2026,7 +1957,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
} catch (e) {
|
||||
_logger.log('🔄 Connection verification failed, reconnecting: $e');
|
||||
try {
|
||||
await connectToServer(_serverUrl!, isRemoteMode: _isRemoteMode, remoteCloudUrl: _remoteCloudUrl);
|
||||
await connectToServer(_serverUrl!);
|
||||
} catch (reconnectError) {
|
||||
_logger.log('🔄 Reconnection failed: $reconnectError');
|
||||
}
|
||||
@@ -2034,59 +1965,6 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start periodic reconnect timer for remote mode (every 30s)
|
||||
void _startRemoteReconnectTimer() {
|
||||
if (!_isRemoteMode) return;
|
||||
if (_remoteReconnectTimer != null) return; // Already running
|
||||
|
||||
_logger.log('🔄 Starting remote reconnect timer (30s interval)');
|
||||
_remoteReconnectTimer = Timer.periodic(const Duration(seconds: 30), (_) async {
|
||||
if (_connectionState == MAConnectionState.connected ||
|
||||
_connectionState == MAConnectionState.authenticated) {
|
||||
_logger.log('🔄 Remote reconnect timer: Already connected, stopping timer');
|
||||
_stopRemoteReconnectTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.log('🔄 Remote reconnect timer: Attempting reconnection...');
|
||||
try {
|
||||
await connectToServer(_serverUrl!, isRemoteMode: _isRemoteMode, remoteCloudUrl: _remoteCloudUrl);
|
||||
_logger.log('🔄 Remote reconnect timer: Reconnection successful');
|
||||
_stopRemoteReconnectTimer();
|
||||
} catch (e) {
|
||||
_logger.log('🔄 Remote reconnect timer: Reconnection failed: $e');
|
||||
// Timer will fire again in 30s
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Stop the remote reconnect timer
|
||||
void _stopRemoteReconnectTimer() {
|
||||
if (_remoteReconnectTimer != null) {
|
||||
_logger.log('🔄 Stopping remote reconnect timer');
|
||||
_remoteReconnectTimer!.cancel();
|
||||
_remoteReconnectTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconnect the API to the existing remote bridge
|
||||
/// Called when RemoteBridge reconnects and API is disconnected
|
||||
Future<void> _reconnectApiToBridge() async {
|
||||
if (_serverUrl == null) {
|
||||
_logger.log('⚠️ No server URL for API reconnect');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
_logger.log('🔄 Reconnecting API to bridge at $_serverUrl');
|
||||
await connectToServer(_serverUrl!, isRemoteMode: _isRemoteMode, remoteCloudUrl: _remoteCloudUrl);
|
||||
_logger.log('✅ API reconnected to bridge successfully');
|
||||
} catch (e) {
|
||||
_logger.log('❌ API reconnect to bridge failed: $e');
|
||||
// The 30s timer will try again
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// LOCAL PLAYER
|
||||
// ============================================================================
|
||||
@@ -2320,71 +2198,17 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
/// - MA 2.7.x: NO proxy, must either:
|
||||
/// - Use local IP with port 8927 exposed, OR
|
||||
/// - Manually configure reverse proxy to route /sendspin to port 8927
|
||||
/// - Remote mode: Uses WebRTC bridge tunnel (ws://localhost:PORT/sendspin)
|
||||
Future<bool> _connectViaSendspin() async {
|
||||
if (_api == null || _serverUrl == null) return false;
|
||||
|
||||
try {
|
||||
final serverVersion = _getServerVersionString();
|
||||
final hasProxy = _serverHasSendspinProxy();
|
||||
_logger.log('Sendspin: Server version $serverVersion, has proxy: $hasProxy, remote: $_isRemoteMode');
|
||||
_logger.log('Sendspin: Server version $serverVersion, has proxy: $hasProxy');
|
||||
|
||||
// In remote mode, connect via the WebRTC bridge tunnel
|
||||
if (_isRemoteMode) {
|
||||
// The bridge provides Sendspin tunnel at ws://localhost:PORT/sendspin
|
||||
// Extract port from the server URL (which is ws://localhost:PORT for remote)
|
||||
final serverUri = Uri.parse(_serverUrl!);
|
||||
if (serverUri.host != 'localhost' && serverUri.host != '127.0.0.1') {
|
||||
_logger.log('⚠️ Sendspin: Remote mode but server URL is not localhost bridge');
|
||||
return false;
|
||||
}
|
||||
|
||||
final bridgeSendspinUrl = 'ws://${serverUri.host}:${serverUri.port}/sendspin';
|
||||
_logger.log('Sendspin: Remote mode - connecting via WebRTC bridge: $bridgeSendspinUrl');
|
||||
|
||||
// Initialize Sendspin service with the bridge's /sendspin endpoint
|
||||
_sendspinService?.dispose();
|
||||
_sendspinService = SendspinService(_serverUrl!); // Base URL for service reference
|
||||
|
||||
// Initialize PCM audio player
|
||||
_pcmAudioPlayer?.dispose();
|
||||
_pcmAudioPlayer = PcmAudioPlayer();
|
||||
final pcmInitialized = await _pcmAudioPlayer!.initialize();
|
||||
if (pcmInitialized) {
|
||||
_logger.log('✅ PCM audio player initialized for Sendspin');
|
||||
await _pcmAudioPlayer!.connectToStream(_sendspinService!.audioDataStream);
|
||||
}
|
||||
|
||||
// Wire up callbacks
|
||||
_sendspinService!.onPlay = _handleSendspinPlay;
|
||||
_sendspinService!.onPause = _handleSendspinPause;
|
||||
_sendspinService!.onStop = _handleSendspinStop;
|
||||
_sendspinService!.onSeek = _handleSendspinSeek;
|
||||
_sendspinService!.onVolume = _handleSendspinVolume;
|
||||
_sendspinService!.onStreamStart = _handleSendspinStreamStart;
|
||||
_sendspinService!.onStreamEnd = _handleSendspinStreamEnd;
|
||||
|
||||
final playerId = await DeviceIdService.getOrCreateDevicePlayerId();
|
||||
_logger.log('Sendspin: Player ID: $playerId');
|
||||
|
||||
// Connect directly to the bridge's /sendspin endpoint
|
||||
// No proxy auth needed - the bridge handles authentication via WebRTC
|
||||
final connected = await _sendspinService!.connectWithUrl(bridgeSendspinUrl);
|
||||
if (connected) {
|
||||
_sendspinConnected = true;
|
||||
_logger.log('✅ Sendspin: Connected via WebRTC bridge tunnel');
|
||||
return true;
|
||||
}
|
||||
_logger.log('⚠️ Sendspin: WebRTC bridge tunnel connection failed');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Local mode - use server URL directly
|
||||
String sendspinServerUrl = _serverUrl!;
|
||||
|
||||
// Initialize Sendspin service with the appropriate server URL
|
||||
// Initialize Sendspin service
|
||||
_sendspinService?.dispose();
|
||||
_sendspinService = SendspinService(sendspinServerUrl);
|
||||
_sendspinService = SendspinService(_serverUrl!);
|
||||
|
||||
// Set auth token for proxy authentication (MA 2.7.1+ or manually configured proxy)
|
||||
final authToken = await SettingsService.getMaAuthToken();
|
||||
@@ -2417,13 +2241,13 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
final playerId = await DeviceIdService.getOrCreateDevicePlayerId();
|
||||
_logger.log('Sendspin: Player ID: $playerId');
|
||||
|
||||
// Parse server URL to determine connection strategy (local mode only - remote handled above)
|
||||
final serverUri = Uri.parse(sendspinServerUrl.startsWith('http')
|
||||
? sendspinServerUrl
|
||||
: 'https://$sendspinServerUrl');
|
||||
// Parse server URL to determine connection strategy
|
||||
final serverUri = Uri.parse(_serverUrl!.startsWith('http')
|
||||
? _serverUrl!
|
||||
: 'https://$_serverUrl');
|
||||
final isLocalIp = _isLocalNetworkHost(serverUri.host);
|
||||
final isHttps = serverUri.scheme == 'https' ||
|
||||
(!sendspinServerUrl.contains('://') && !isLocalIp);
|
||||
(!_serverUrl!.contains('://') && !isLocalIp);
|
||||
|
||||
// Strategy 1: For local IPs, connect directly to Sendspin port 8927
|
||||
if (isLocalIp) {
|
||||
@@ -2988,14 +2812,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
Map<String, dynamic>? metadata;
|
||||
if (imageUrl != null) {
|
||||
var finalImageUrl = imageUrl;
|
||||
// In remote mode, don't use imageproxy (can't reach MA server through WebRTC tunnel)
|
||||
// Use the original URL directly if it's an external HTTPS URL
|
||||
if (_api?.isRemoteMode == true) {
|
||||
// Keep external URLs as-is, they should work directly
|
||||
if (!imageUrl.startsWith('https://')) {
|
||||
finalImageUrl = imageUrl; // May not load, but better than broken imageproxy
|
||||
}
|
||||
} else if (_serverUrl != null && !_serverUrl!.startsWith('ws://') && !_serverUrl!.startsWith('wss://')) {
|
||||
if (_serverUrl != null) {
|
||||
try {
|
||||
final imgUri = Uri.parse(imageUrl);
|
||||
final queryString = imgUri.query;
|
||||
@@ -3235,9 +3052,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
artist ??= 'Unknown Artist';
|
||||
|
||||
// In remote mode, don't use imageproxy (can't reach MA server through WebRTC tunnel)
|
||||
if (imageUrl != null && _api?.isRemoteMode != true && _serverUrl != null &&
|
||||
!_serverUrl!.startsWith('ws://') && !_serverUrl!.startsWith('wss://')) {
|
||||
if (imageUrl != null && _serverUrl != null) {
|
||||
try {
|
||||
final imgUri = Uri.parse(imageUrl);
|
||||
final queryString = imgUri.query;
|
||||
@@ -5086,8 +4901,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
// Fetch tracks from API (not cached - too many items)
|
||||
// Skip in remote mode to keep connection responsive
|
||||
if (_api != null && !_api!.isRemoteMode) {
|
||||
if (_api != null) {
|
||||
try {
|
||||
_tracks = await _api!.getTracks(
|
||||
limit: LibraryConstants.maxLibraryItems,
|
||||
@@ -5097,8 +4911,6 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Failed to fetch tracks: $e');
|
||||
}
|
||||
} else if (_api?.isRemoteMode == true) {
|
||||
_logger.log('🌐 Remote mode: skipping tracks fetch');
|
||||
}
|
||||
|
||||
_isLoading = false;
|
||||
@@ -5120,13 +4932,6 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
Future<void> _syncLibraryInBackground() async {
|
||||
if (_api == null) return;
|
||||
|
||||
// In remote mode, delay sync to let player/queue operations complete first
|
||||
if (_api!.isRemoteMode) {
|
||||
_logger.log('🌐 Remote mode: delaying library sync by 3 seconds');
|
||||
await Future.delayed(const Duration(seconds: 3));
|
||||
if (_api == null || !isConnected) return; // Check still connected
|
||||
}
|
||||
|
||||
final syncService = SyncService.instance;
|
||||
|
||||
// Listen for sync completion to update our lists
|
||||
@@ -5141,14 +4946,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
syncService.addListener(onSyncComplete);
|
||||
|
||||
// In remote mode, force sync but use gentler approach (handled in SyncService)
|
||||
if (_api!.isRemoteMode) {
|
||||
_logger.log('🌐 Remote mode: starting gentle library sync');
|
||||
await syncService.forceSync(_api!, providerInstanceIds: providerIdsForApiCalls);
|
||||
} else {
|
||||
await syncService.syncFromApi(_api!, providerInstanceIds: providerIdsForApiCalls);
|
||||
}
|
||||
await syncService.syncFromApi(_api!, providerInstanceIds: providerIdsForApiCalls);
|
||||
}
|
||||
|
||||
/// Load radio stations from the library
|
||||
@@ -6219,8 +6017,6 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
_sleepTimer?.cancel();
|
||||
_sleepTimerDisplayTimer?.cancel();
|
||||
_idleServiceTimer?.cancel();
|
||||
_remoteReconnectTimer?.cancel();
|
||||
_remoteBridgeStateSubscription?.cancel();
|
||||
_connectionStateSubscription?.cancel();
|
||||
_localPlayerEventSubscription?.cancel();
|
||||
_playerUpdatedEventSubscription?.cancel();
|
||||
|
||||
@@ -41,12 +41,10 @@ class _DebugLogScreenState extends State<DebugLogScreen> {
|
||||
_logger.entries.where((e) => e.level.index >= _filterLevel.index).toList();
|
||||
|
||||
void _copyLogs() {
|
||||
// Copy only the filtered entries that are currently displayed
|
||||
final filteredLogs = _filteredEntries.map((e) => e.formatted).join('\n');
|
||||
Clipboard.setData(ClipboardData(text: filteredLogs));
|
||||
Clipboard.setData(ClipboardData(text: _logger.getAllLogs()));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('${S.of(context)!.logsCopied} (${_filteredEntries.length} entries)'),
|
||||
content: Text(S.of(context)!.logsCopied),
|
||||
backgroundColor: Colors.green,
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
@@ -63,8 +61,6 @@ class _DebugLogScreenState extends State<DebugLogScreen> {
|
||||
report,
|
||||
subject: S.of(context)!.ensembleBugReport,
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.error('Share failed', error: e);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isGeneratingReport = false);
|
||||
|
||||
+75
-218
@@ -8,7 +8,6 @@ import '../services/auth/auth_strategy.dart';
|
||||
import '../widgets/debug/debug_console.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import 'home_screen.dart';
|
||||
import 'qr_scanner_screen.dart';
|
||||
|
||||
enum ConnectionMode { local, remote }
|
||||
|
||||
@@ -29,6 +28,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
final TextEditingController _remoteIdController = TextEditingController(); // Remote Access ID
|
||||
final FocusNode _usernameFocusNode = FocusNode();
|
||||
|
||||
ConnectionMode _connectionMode = ConnectionMode.local;
|
||||
bool _isConnecting = false;
|
||||
bool _isDetectingAuth = false;
|
||||
AuthStrategy? _detectedAuthStrategy;
|
||||
@@ -39,9 +39,6 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
String? _resolvedServerUrl; // The actual URL after fallback (e.g., HTTP if HTTPS failed)
|
||||
bool _usedHttpFallback = false; // True if HTTPS failed and we fell back to HTTP
|
||||
|
||||
// Remote connection state
|
||||
ConnectionMode _connectionMode = ConnectionMode.local;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -82,8 +79,6 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
_passwordController.dispose();
|
||||
_remoteIdController.dispose();
|
||||
_usernameFocusNode.dispose();
|
||||
// Note: Don't stop _remoteBridge here - it needs to stay alive for the session
|
||||
// It will be stopped when the app closes or user disconnects
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -452,9 +447,6 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
|
||||
if (provider.isConnected) {
|
||||
// Clear remote access ID since this is a direct/local connection
|
||||
await SettingsService.clearRemoteAccessId();
|
||||
|
||||
// For first-time users, wait for player selection so the welcome
|
||||
// overlay can appear immediately without home screen flash.
|
||||
// This matches the logic in AppStartup._checkAndConnect().
|
||||
@@ -489,19 +481,18 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect via remote bridge (WebRTC tunnel)
|
||||
Future<void> _connectRemote() async {
|
||||
final remoteId = _remoteIdController.text.trim();
|
||||
final username = _usernameController.text.trim();
|
||||
final password = _passwordController.text.trim();
|
||||
|
||||
if (remoteId.isEmpty) {
|
||||
setState(() {
|
||||
_error = S.of(context)!.pleaseEnterRemoteId;
|
||||
_error = 'Please enter a Remote Access ID';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final username = _usernameController.text.trim();
|
||||
final password = _passwordController.text.trim();
|
||||
|
||||
if (username.isEmpty || password.isEmpty) {
|
||||
setState(() {
|
||||
_error = S.of(context)!.pleaseEnterCredentials;
|
||||
@@ -514,57 +505,22 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
_error = null;
|
||||
});
|
||||
|
||||
_addDebugLog('Starting remote connection to: $remoteId');
|
||||
_addDebugLog('Connecting to remote server: $remoteId');
|
||||
|
||||
try {
|
||||
// Start the remote bridge via provider (WebView is already in widget tree)
|
||||
final provider = context.read<MusicAssistantProvider>();
|
||||
final port = await provider.startRemoteBridge(remoteId, username, password);
|
||||
|
||||
if (port == null) {
|
||||
setState(() {
|
||||
_error = S.of(context)!.remoteConnectionFailed;
|
||||
_isConnecting = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Connect via remote access
|
||||
final success = await provider.connectRemote(remoteId, username, password);
|
||||
|
||||
_addDebugLog('Remote bridge started on port $port');
|
||||
if (success) {
|
||||
_addDebugLog('Remote connection successful');
|
||||
|
||||
// Save credentials BEFORE connecting - needed for MA authentication via bridge
|
||||
await SettingsService.setUsername(username);
|
||||
await SettingsService.setPassword(password);
|
||||
|
||||
// Connect to the local bridge endpoint
|
||||
final serverUrl = 'ws://localhost:$port';
|
||||
|
||||
_addDebugLog('Connecting to bridge at $serverUrl');
|
||||
// Pass remoteId as cloud URL for Sendspin to connect directly
|
||||
await provider.connectToServer(serverUrl, isRemoteMode: true, remoteCloudUrl: remoteId);
|
||||
|
||||
// Wait for connection
|
||||
for (int i = 0; i < 10; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
if (provider.isConnected) break;
|
||||
}
|
||||
|
||||
if (provider.isConnected) {
|
||||
_addDebugLog('Connected successfully via remote bridge');
|
||||
|
||||
// Save remote access ID and credentials for future auto-reconnect
|
||||
// Save credentials for future use
|
||||
await SettingsService.setRemoteAccessId(remoteId);
|
||||
await SettingsService.setUsername(username);
|
||||
await SettingsService.setPassword(password);
|
||||
|
||||
// For first-time users, wait for player selection
|
||||
final hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||
if (!hasCompletedOnboarding) {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 250));
|
||||
if (provider.selectedPlayer != null) break;
|
||||
}
|
||||
}
|
||||
|
||||
// Navigate to home screen
|
||||
if (mounted) {
|
||||
FocusScope.of(context).unfocus();
|
||||
@@ -574,14 +530,14 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
} else {
|
||||
setState(() {
|
||||
_error = S.of(context)!.connectionFailed;
|
||||
_error = 'Remote connection failed. Check your credentials and Remote Access ID.';
|
||||
_isConnecting = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
_addDebugLog('Remote connection error: $e');
|
||||
setState(() {
|
||||
_error = 'Remote connection failed: ${e.toString()}';
|
||||
_error = 'Connection failed: ${e.toString()}';
|
||||
_isConnecting = false;
|
||||
});
|
||||
}
|
||||
@@ -621,114 +577,47 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Connection Mode Toggle
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceVariant.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: _isConnecting ? null : () {
|
||||
setState(() {
|
||||
_connectionMode = ConnectionMode.local;
|
||||
_error = null;
|
||||
_detectedAuthStrategy = null;
|
||||
_detectedAuthType = null;
|
||||
});
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: _connectionMode == ConnectionMode.local
|
||||
? colorScheme.primary
|
||||
: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.home_rounded,
|
||||
size: 20,
|
||||
color: _connectionMode == ConnectionMode.local
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurface.withOpacity(0.6),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
S.of(context)!.localConnection,
|
||||
style: TextStyle(
|
||||
color: _connectionMode == ConnectionMode.local
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurface.withOpacity(0.6),
|
||||
fontWeight: _connectionMode == ConnectionMode.local
|
||||
? FontWeight.w600
|
||||
: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: _isConnecting ? null : () {
|
||||
setState(() {
|
||||
_connectionMode = ConnectionMode.remote;
|
||||
_error = null;
|
||||
_detectedAuthStrategy = null;
|
||||
_detectedAuthType = null;
|
||||
});
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: _connectionMode == ConnectionMode.remote
|
||||
? colorScheme.primary
|
||||
: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.cloud_rounded,
|
||||
size: 20,
|
||||
color: _connectionMode == ConnectionMode.remote
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurface.withOpacity(0.6),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
S.of(context)!.remoteConnection,
|
||||
style: TextStyle(
|
||||
color: _connectionMode == ConnectionMode.remote
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurface.withOpacity(0.6),
|
||||
fontWeight: _connectionMode == ConnectionMode.remote
|
||||
? FontWeight.w600
|
||||
: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
// Connection mode selector
|
||||
SegmentedButton<ConnectionMode>(
|
||||
segments: [
|
||||
ButtonSegment<ConnectionMode>(
|
||||
value: ConnectionMode.local,
|
||||
label: Text('Local'),
|
||||
icon: Icon(Icons.home_rounded),
|
||||
),
|
||||
ButtonSegment<ConnectionMode>(
|
||||
value: ConnectionMode.remote,
|
||||
label: Text('Remote'),
|
||||
icon: Icon(Icons.cloud_rounded),
|
||||
),
|
||||
],
|
||||
selected: {_connectionMode},
|
||||
onSelectionChanged: _isConnecting || _isDetectingAuth
|
||||
? null
|
||||
: (Set<ConnectionMode> selection) {
|
||||
setState(() {
|
||||
_connectionMode = selection.first;
|
||||
_error = null;
|
||||
_detectedAuthStrategy = null;
|
||||
_detectedAuthType = null;
|
||||
});
|
||||
},
|
||||
style: ButtonStyle(
|
||||
backgroundColor: WidgetStateProperty.resolveWith((states) {
|
||||
if (states.contains(WidgetState.selected)) {
|
||||
return colorScheme.primaryContainer;
|
||||
}
|
||||
return colorScheme.surfaceVariant.withOpacity(0.3);
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// REMOTE MODE: Remote Access ID + Credentials
|
||||
// Remote Access UI
|
||||
if (_connectionMode == ConnectionMode.remote) ...[
|
||||
Text(
|
||||
S.of(context)!.remoteAccessId,
|
||||
'Remote Access ID',
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
color: colorScheme.onBackground,
|
||||
fontWeight: FontWeight.w500,
|
||||
@@ -736,7 +625,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
S.of(context)!.remoteAccessIdHint,
|
||||
'Find this in Music Assistant Settings → Remote Access',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onBackground.withOpacity(0.6),
|
||||
fontSize: 12,
|
||||
@@ -744,64 +633,31 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
IntrinsicHeight(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _remoteIdController,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'ABCD1234-EFGH5-6IJKL-MNOP7890',
|
||||
hintStyle: TextStyle(color: colorScheme.onSurface.withOpacity(0.38)),
|
||||
filled: true,
|
||||
fillColor: colorScheme.surfaceVariant.withOpacity(0.3),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: Icon(
|
||||
Icons.vpn_key_rounded,
|
||||
color: colorScheme.onSurface.withOpacity(0.54),
|
||||
),
|
||||
),
|
||||
enabled: !_isConnecting,
|
||||
keyboardType: TextInputType.text,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceVariant.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4),
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
Icons.qr_code_scanner_rounded,
|
||||
color: colorScheme.onSurface.withOpacity(0.54),
|
||||
),
|
||||
onPressed: _isConnecting ? null : () async {
|
||||
final result = await Navigator.of(context).push<String>(
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const QrScannerScreen(),
|
||||
),
|
||||
);
|
||||
if (result != null && result.isNotEmpty) {
|
||||
_remoteIdController.text = result;
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
TextField(
|
||||
controller: _remoteIdController,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'XXXX-XXXX-XXXX-XXXX',
|
||||
hintStyle: TextStyle(color: colorScheme.onSurface.withOpacity(0.38)),
|
||||
filled: true,
|
||||
fillColor: colorScheme.surfaceVariant.withOpacity(0.3),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: Icon(
|
||||
Icons.vpn_key_rounded,
|
||||
color: colorScheme.onSurface.withOpacity(0.54),
|
||||
),
|
||||
),
|
||||
enabled: !_isConnecting,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Username for remote
|
||||
// Username
|
||||
Text(
|
||||
S.of(context)!.username,
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
@@ -813,7 +669,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
|
||||
TextField(
|
||||
controller: _usernameController,
|
||||
focusNode: _connectionMode == ConnectionMode.remote ? _usernameFocusNode : null,
|
||||
focusNode: _usernameFocusNode,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
decoration: InputDecoration(
|
||||
hintText: S.of(context)!.username,
|
||||
@@ -835,7 +691,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Password for remote
|
||||
// Password
|
||||
Text(
|
||||
S.of(context)!.password,
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
@@ -868,11 +724,12 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
onSubmitted: (_) => _connectRemote(),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
|
||||
// LOCAL MODE: Server URL, Port, etc.
|
||||
// Local connection UI
|
||||
if (_connectionMode == ConnectionMode.local) ...[
|
||||
// Server URL
|
||||
Text(
|
||||
S.of(context)!.serverAddress,
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
@@ -1217,7 +1074,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
], // End of local mode conditional
|
||||
], // End of local connection UI
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
@@ -1260,7 +1117,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Connect button (changes based on state)
|
||||
// Connect button (changes based on state and mode)
|
||||
ElevatedButton(
|
||||
onPressed: (_isConnecting || _isDetectingAuth)
|
||||
? null
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../providers/music_assistant_provider.dart';
|
||||
@@ -227,21 +226,6 @@ class _NewHomeScreenState extends State<NewHomeScreen> with AutomaticKeepAliveCl
|
||||
titleSpacing: 0,
|
||||
centerTitle: false,
|
||||
actions: [
|
||||
// Copy logs button for debugging
|
||||
IconButton(
|
||||
icon: const Icon(Icons.bug_report_outlined, size: 20),
|
||||
onPressed: () {
|
||||
final logs = DebugLogger().entries.map((e) => e.formatted).join('\n');
|
||||
Clipboard.setData(ClipboardData(text: logs));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('${DebugLogger().entries.length} log entries copied'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
},
|
||||
tooltip: 'Copy logs',
|
||||
),
|
||||
// Sync indicator - shows when library is syncing in background
|
||||
ListenableBuilder(
|
||||
listenable: SyncService.instance,
|
||||
|
||||
@@ -1502,8 +1502,8 @@ class _NewLibraryScreenState extends State<NewLibraryScreen>
|
||||
controller: _pageController,
|
||||
onPageChanged: _onPageChanged,
|
||||
itemCount: _tabCount,
|
||||
// Use default physics - custom physics may cause issues with Flutter 3.38
|
||||
physics: const PageScrollPhysics(),
|
||||
// Faster settling so vertical scroll works sooner after swipe
|
||||
physics: const _FastPageScrollPhysics(),
|
||||
itemBuilder: (context, index) => _buildTabAtIndex(context, l10n, index),
|
||||
),
|
||||
),
|
||||
@@ -4708,9 +4708,9 @@ class _FastPageScrollPhysics extends PageScrollPhysics {
|
||||
|
||||
@override
|
||||
SpringDescription get spring => const SpringDescription(
|
||||
mass: 80, // Increased mass for more controlled movement
|
||||
stiffness: 100, // Reduced stiffness to prevent over-snapping
|
||||
damping: 1.2, // Slightly over-damped to prevent overshoot
|
||||
mass: 50, // Lower mass = faster movement
|
||||
stiffness: 500, // Higher stiffness = snappier
|
||||
damping: 1.0, // Critical damping for no overshoot
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
/// A screen for scanning QR codes to get the Remote Access ID.
|
||||
class QrScannerScreen extends StatefulWidget {
|
||||
const QrScannerScreen({super.key});
|
||||
|
||||
@override
|
||||
State<QrScannerScreen> createState() => _QrScannerScreenState();
|
||||
}
|
||||
|
||||
class _QrScannerScreenState extends State<QrScannerScreen> {
|
||||
late final MobileScannerController _controller;
|
||||
bool _hasScanned = false;
|
||||
String _statusMessage = '';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.normal,
|
||||
facing: CameraFacing.back,
|
||||
formats: [BarcodeFormat.qrCode], // Only scan QR codes
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onDetect(BarcodeCapture capture) {
|
||||
if (_hasScanned) return;
|
||||
|
||||
final List<Barcode> barcodes = capture.barcodes;
|
||||
for (final barcode in barcodes) {
|
||||
final String? code = barcode.rawValue;
|
||||
if (code != null && code.isNotEmpty) {
|
||||
final remoteId = _extractRemoteId(code);
|
||||
|
||||
if (remoteId != null && remoteId.isNotEmpty) {
|
||||
_hasScanned = true;
|
||||
Navigator.of(context).pop(remoteId);
|
||||
return;
|
||||
} else {
|
||||
// Show what was scanned for debugging
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Scanned: $code'),
|
||||
duration: const Duration(seconds: 5),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the remote ID from various QR code formats
|
||||
String? _extractRemoteId(String code) {
|
||||
// Format 1: Raw remote ID (alphanumeric)
|
||||
if (RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(code) && code.length >= 8) {
|
||||
return code;
|
||||
}
|
||||
|
||||
// Format 2: ma://remote/<id>
|
||||
if (code.startsWith('ma://remote/')) {
|
||||
return code.replaceFirst('ma://remote/', '');
|
||||
}
|
||||
|
||||
// Format 3: URL from app.music-assistant.io
|
||||
// Examples:
|
||||
// - https://app.music-assistant.io/?cloudInstanceId=<id>
|
||||
// - https://app.music-assistant.io/#/home?cloudInstanceId=<id>
|
||||
if (code.contains('music-assistant.io')) {
|
||||
final uri = Uri.tryParse(code);
|
||||
if (uri != null) {
|
||||
// Check query parameters in main URL
|
||||
final queryParams = ['cloudInstanceId', 'cloud_instance_id', 'remoteid', 'remote_id', 'id'];
|
||||
for (final param in queryParams) {
|
||||
final value = uri.queryParameters[param];
|
||||
if (value != null && value.isNotEmpty) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// Check fragment (hash) for query params: #/home?cloudInstanceId=xxx
|
||||
final fragment = uri.fragment;
|
||||
if (fragment.contains('?')) {
|
||||
final fragmentQuery = fragment.split('?').last;
|
||||
final fragmentParams = Uri.splitQueryString(fragmentQuery);
|
||||
for (final param in queryParams) {
|
||||
final value = fragmentParams[param];
|
||||
if (value != null && value.isNotEmpty) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if ID is in path segments
|
||||
for (final segment in uri.pathSegments) {
|
||||
if (segment.length >= 8 && RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(segment)) {
|
||||
return segment;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Format 4: Other URL formats - try to extract from query params or path
|
||||
if (code.contains('://')) {
|
||||
final uri = Uri.tryParse(code);
|
||||
if (uri != null) {
|
||||
// Check common query param names
|
||||
for (final param in ['id', 'remoteid', 'remote_id', 'cloudInstanceId']) {
|
||||
final value = uri.queryParameters[param];
|
||||
if (value != null && value.isNotEmpty) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
// Last path segment if it looks like an ID
|
||||
if (uri.pathSegments.isNotEmpty) {
|
||||
final last = uri.pathSegments.last;
|
||||
if (last.length >= 8 && RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(last)) {
|
||||
return last;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
title: Text(S.of(context)!.scanQrCode),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
actions: [
|
||||
// Toggle torch
|
||||
IconButton(
|
||||
icon: ValueListenableBuilder(
|
||||
valueListenable: _controller,
|
||||
builder: (context, state, child) {
|
||||
return Icon(
|
||||
state.torchState == TorchState.on
|
||||
? Icons.flash_on
|
||||
: Icons.flash_off,
|
||||
);
|
||||
},
|
||||
),
|
||||
onPressed: () => _controller.toggleTorch(),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
// Camera preview
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
onDetect: _onDetect,
|
||||
errorBuilder: (context, error, child) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.camera_alt_outlined,
|
||||
size: 64,
|
||||
color: colorScheme.error,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Camera error: ${error.errorCode.name}',
|
||||
style: TextStyle(color: colorScheme.error),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
error.errorDetails?.message ?? S.of(context)!.cameraPermissionDenied,
|
||||
style: TextStyle(color: colorScheme.error.withOpacity(0.7)),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
// Scan overlay with instruction
|
||||
Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
// Scan frame
|
||||
Container(
|
||||
width: 280,
|
||||
height: 280,
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
width: 2,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
// Instruction text
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
margin: const EdgeInsets.symmetric(horizontal: 24),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withOpacity(0.7),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
S.of(context)!.pointCameraAtQr,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
if (_statusMessage.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_statusMessage,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.7),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import 'basic_auth_strategy.dart';
|
||||
import 'authelia_strategy.dart';
|
||||
import 'ma_auth_strategy.dart';
|
||||
import '../debug_logger.dart';
|
||||
import '../../constants/network.dart';
|
||||
|
||||
/// Central authentication manager
|
||||
/// Manages auth strategy selection, auto-detection, and credential lifecycle
|
||||
@@ -66,18 +65,16 @@ class AuthManager {
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Normalize a server URL with appropriate protocol and port
|
||||
/// For local IP addresses without an explicit port, defaults to MA port 8095
|
||||
/// Normalize a server URL with appropriate protocol
|
||||
String _normalizeUrl(String url) {
|
||||
var baseUrl = url.trim();
|
||||
|
||||
// Check if URL already has a port specified (before adding protocol)
|
||||
// Port can be specified as host:port or after protocol as http://host:port
|
||||
bool hasExplicitPort = _hasExplicitPort(baseUrl);
|
||||
|
||||
var baseUrl = url;
|
||||
if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
|
||||
// Use http for local IPs, https for domains
|
||||
if (_isLocalAddress(baseUrl)) {
|
||||
if (baseUrl.startsWith('192.') ||
|
||||
baseUrl.startsWith('10.') ||
|
||||
baseUrl.startsWith('172.') ||
|
||||
baseUrl == 'localhost' ||
|
||||
baseUrl.startsWith('127.')) {
|
||||
baseUrl = 'http://$baseUrl';
|
||||
} else if (baseUrl.endsWith('.ts.net') || baseUrl.contains('.ts.net:')) {
|
||||
// Tailscale URLs - default to http:// since VPN tunnel is already encrypted
|
||||
@@ -87,80 +84,9 @@ class AuthManager {
|
||||
baseUrl = 'https://$baseUrl';
|
||||
}
|
||||
}
|
||||
|
||||
// For local addresses without explicit port, add default MA port
|
||||
// This handles the common case of MA as HAOS add-on where port 8095 is needed
|
||||
if (!hasExplicitPort) {
|
||||
final uri = Uri.parse(baseUrl);
|
||||
if (_isLocalAddress(uri.host)) {
|
||||
baseUrl = Uri(
|
||||
scheme: uri.scheme,
|
||||
host: uri.host,
|
||||
port: NetworkConstants.defaultWsPort,
|
||||
path: uri.path.isEmpty ? null : uri.path,
|
||||
).toString();
|
||||
_logger.log('🔗 Local address without port - defaulting to MA port ${NetworkConstants.defaultWsPort}');
|
||||
}
|
||||
}
|
||||
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
/// Check if a URL string has an explicit port specified
|
||||
bool _hasExplicitPort(String url) {
|
||||
// Remove protocol if present
|
||||
var hostPart = url;
|
||||
if (hostPart.startsWith('http://')) {
|
||||
hostPart = hostPart.substring(7);
|
||||
} else if (hostPart.startsWith('https://')) {
|
||||
hostPart = hostPart.substring(8);
|
||||
}
|
||||
|
||||
// Remove path if present
|
||||
final pathIndex = hostPart.indexOf('/');
|
||||
if (pathIndex != -1) {
|
||||
hostPart = hostPart.substring(0, pathIndex);
|
||||
}
|
||||
|
||||
// Check for port (host:port pattern)
|
||||
// Need to handle IPv6 addresses like [::1]:8095
|
||||
if (hostPart.startsWith('[')) {
|
||||
// IPv6 address
|
||||
final closeBracket = hostPart.indexOf(']');
|
||||
if (closeBracket != -1 && closeBracket < hostPart.length - 1) {
|
||||
return hostPart[closeBracket + 1] == ':';
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
// IPv4 or hostname - check for colon followed by digits
|
||||
final colonIndex = hostPart.lastIndexOf(':');
|
||||
if (colonIndex != -1) {
|
||||
final portPart = hostPart.substring(colonIndex + 1);
|
||||
return int.tryParse(portPart) != null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if an address is a local/private address (without protocol)
|
||||
bool _isLocalAddress(String address) {
|
||||
// Remove port if present for checking
|
||||
var host = address;
|
||||
final colonIndex = host.lastIndexOf(':');
|
||||
if (colonIndex != -1 && int.tryParse(host.substring(colonIndex + 1)) != null) {
|
||||
host = host.substring(0, colonIndex);
|
||||
}
|
||||
|
||||
return host.startsWith('192.168.') ||
|
||||
host.startsWith('192.') ||
|
||||
host.startsWith('10.') ||
|
||||
host.startsWith('172.') ||
|
||||
host == 'localhost' ||
|
||||
host.startsWith('127.') ||
|
||||
host.endsWith('.local') ||
|
||||
host.endsWith('.ts.net');
|
||||
}
|
||||
|
||||
/// Check if a hostname is a local/private IP address
|
||||
bool _isLocalIpAddress(String host) {
|
||||
return host.startsWith('192.168.') ||
|
||||
|
||||
@@ -7,9 +7,6 @@ enum ErrorType {
|
||||
network,
|
||||
playback,
|
||||
library,
|
||||
remote, // Remote connection (WebRTC) errors
|
||||
dataChannel, // WebRTC data channel errors
|
||||
signaling, // WebRTC signaling server errors
|
||||
unknown,
|
||||
}
|
||||
|
||||
@@ -110,41 +107,6 @@ class ErrorHandler {
|
||||
);
|
||||
}
|
||||
|
||||
// WebRTC/Remote connection errors
|
||||
if (errorStr.contains('webrtc') ||
|
||||
errorStr.contains('remote peer') ||
|
||||
errorStr.contains('remote server disconnected')) {
|
||||
return ErrorInfo(
|
||||
type: ErrorType.remote,
|
||||
userMessage: 'Remote connection lost. Attempting to reconnect...',
|
||||
technicalMessage: error.toString(),
|
||||
canRetry: true,
|
||||
);
|
||||
}
|
||||
|
||||
// Data channel errors
|
||||
if (errorStr.contains('data channel') ||
|
||||
errorStr.contains('datachannel')) {
|
||||
return ErrorInfo(
|
||||
type: ErrorType.dataChannel,
|
||||
userMessage: 'Remote data connection failed. Please try reconnecting.',
|
||||
technicalMessage: error.toString(),
|
||||
canRetry: true,
|
||||
);
|
||||
}
|
||||
|
||||
// Signaling errors
|
||||
if (errorStr.contains('signaling') ||
|
||||
errorStr.contains('ice') ||
|
||||
errorStr.contains('peer connection failed')) {
|
||||
return ErrorInfo(
|
||||
type: ErrorType.signaling,
|
||||
userMessage: 'Failed to establish remote connection. Please try again.',
|
||||
technicalMessage: error.toString(),
|
||||
canRetry: true,
|
||||
);
|
||||
}
|
||||
|
||||
// Unknown errors
|
||||
return ErrorInfo(
|
||||
type: ErrorType.unknown,
|
||||
|
||||
@@ -25,20 +25,6 @@ enum MAConnectionState {
|
||||
error,
|
||||
}
|
||||
|
||||
/// Wrapper for pending requests with timestamp for age-based cleanup
|
||||
class _PendingRequest {
|
||||
final Completer<Map<String, dynamic>> completer;
|
||||
final DateTime createdAt;
|
||||
|
||||
_PendingRequest({required this.completer, DateTime? createdAt})
|
||||
: createdAt = createdAt ?? DateTime.now();
|
||||
|
||||
bool get isStale {
|
||||
const staleThreshold = Duration(minutes: 2);
|
||||
return DateTime.now().difference(createdAt) > staleThreshold;
|
||||
}
|
||||
}
|
||||
|
||||
class MusicAssistantAPI {
|
||||
final String serverUrl;
|
||||
final AuthManager authManager;
|
||||
@@ -52,7 +38,7 @@ class MusicAssistantAPI {
|
||||
MAConnectionState _currentState = MAConnectionState.disconnected;
|
||||
MAConnectionState get currentConnectionState => _currentState;
|
||||
|
||||
final Map<String, _PendingRequest> _pendingRequests = {};
|
||||
final Map<String, Completer<Map<String, dynamic>>> _pendingRequests = {};
|
||||
final Map<String, StreamController<Map<String, dynamic>>> _eventStreams = {};
|
||||
|
||||
Completer<void>? _connectionCompleter;
|
||||
@@ -79,12 +65,6 @@ class MusicAssistantAPI {
|
||||
final Map<String, ProviderManifest> _providerManifests = {};
|
||||
Map<String, ProviderManifest> get providerManifests => _providerManifests;
|
||||
|
||||
// Remote mode flag - when true, images go through WebRTC bridge which doesn't support HTTP
|
||||
// In this mode, we use external CDN URLs directly instead of imageproxy
|
||||
bool _isRemoteMode = false;
|
||||
bool get isRemoteMode => _isRemoteMode;
|
||||
set isRemoteMode(bool value) => _isRemoteMode = value;
|
||||
|
||||
MusicAssistantAPI(this.serverUrl, this.authManager);
|
||||
|
||||
// Guard to prevent multiple simultaneous connection attempts
|
||||
@@ -305,15 +285,15 @@ class MusicAssistantAPI {
|
||||
|
||||
// Handle response to a request
|
||||
if (messageId != null && _pendingRequests.containsKey(messageId)) {
|
||||
final pending = _pendingRequests.remove(messageId);
|
||||
final completer = _pendingRequests.remove(messageId);
|
||||
|
||||
if (data.containsKey('error_code')) {
|
||||
_logger.log('Command error: ${data['error_code']} - ${data['details']}');
|
||||
pending!.completer.completeError(
|
||||
completer!.completeError(
|
||||
Exception('${data['error_code']}: ${data['details']}'),
|
||||
);
|
||||
} else {
|
||||
pending!.completer.complete(data);
|
||||
completer!.complete(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -372,9 +352,6 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale requests before checking limits
|
||||
_cleanupStaleRequests();
|
||||
|
||||
// Prevent memory leaks by limiting pending requests
|
||||
if (_pendingRequests.length >= NetworkConstants.maxPendingRequests) {
|
||||
throw Exception(
|
||||
@@ -385,7 +362,7 @@ class MusicAssistantAPI {
|
||||
|
||||
final messageId = _uuid.v4();
|
||||
final completer = Completer<Map<String, dynamic>>();
|
||||
_pendingRequests[messageId] = _PendingRequest(completer: completer);
|
||||
_pendingRequests[messageId] = completer;
|
||||
|
||||
final message = {
|
||||
'message_id': messageId,
|
||||
@@ -408,27 +385,6 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clean up stale pending requests that have been waiting too long
|
||||
void _cleanupStaleRequests() {
|
||||
final staleIds = <String>[];
|
||||
for (final entry in _pendingRequests.entries) {
|
||||
if (entry.value.isStale && !entry.value.completer.isCompleted) {
|
||||
staleIds.add(entry.key);
|
||||
}
|
||||
}
|
||||
if (staleIds.isNotEmpty) {
|
||||
_logger.log('Cleanup: Removing ${staleIds.length} stale pending requests');
|
||||
for (final id in staleIds) {
|
||||
final pending = _pendingRequests.remove(id);
|
||||
if (pending != null && !pending.completer.isCompleted) {
|
||||
pending.completer.completeError(
|
||||
TimeoutException('Request expired after 2 minutes'),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Library browsing methods
|
||||
Future<List<Artist>> getArtists({
|
||||
int? limit,
|
||||
@@ -3260,12 +3216,6 @@ class MusicAssistantAPI {
|
||||
return null;
|
||||
}
|
||||
|
||||
// In remote mode (WebRTC bridge), HTTP requests don't work through the tunnel
|
||||
// So we need to use external CDN URLs directly when available
|
||||
if (_isRemoteMode) {
|
||||
return _getImageUrlForRemoteMode(images, size);
|
||||
}
|
||||
|
||||
// Try to find a non-remotely accessible image first (prefer local/opensubsonic)
|
||||
Map<String, dynamic>? selectedImage;
|
||||
for (var img in images) {
|
||||
@@ -3328,107 +3278,6 @@ class MusicAssistantAPI {
|
||||
return '$baseUrl/imageproxy?provider=${Uri.encodeComponent(provider ?? "")}&size=$size&fmt=jpeg&path=${Uri.encodeComponent(imagePath)}';
|
||||
}
|
||||
|
||||
/// Get image URL for remote mode - uses external CDN URLs directly
|
||||
/// since HTTP requests don't work through the WebRTC bridge
|
||||
String? _getImageUrlForRemoteMode(List<dynamic> images, int size) {
|
||||
// Known external CDN domains that are publicly accessible
|
||||
const externalDomains = [
|
||||
'i.scdn.co', // Spotify
|
||||
'mosaic.scdn.co', // Spotify playlists
|
||||
'image-cdn-ak.spotifycdn.com', // Spotify
|
||||
'cdns-images.dzcdn.net', // Deezer
|
||||
'resources.tidal.com', // Tidal
|
||||
'e-cdns-images.dzcdn.net', // Deezer
|
||||
'is1-ssl.mzstatic.com', // Apple Music
|
||||
'is2-ssl.mzstatic.com', // Apple Music
|
||||
'is3-ssl.mzstatic.com', // Apple Music
|
||||
'is4-ssl.mzstatic.com', // Apple Music
|
||||
'is5-ssl.mzstatic.com', // Apple Music
|
||||
'lastfm.freetls.fastly.net', // Last.fm
|
||||
'coverartarchive.org', // MusicBrainz
|
||||
'archive.org', // Internet Archive
|
||||
'fanart.tv', // Fanart.tv
|
||||
];
|
||||
|
||||
// First pass: look for images with paths that are external URLs
|
||||
for (var img in images) {
|
||||
final imgMap = img as Map<String, dynamic>;
|
||||
final path = imgMap['path'] as String?;
|
||||
if (path == null) continue;
|
||||
|
||||
// Check if path is already an external URL
|
||||
if (path.startsWith('https://')) {
|
||||
try {
|
||||
final uri = Uri.parse(path);
|
||||
|
||||
// If URL contains imageproxy with a size parameter, replace with requested size
|
||||
if (uri.path.contains('imageproxy') && uri.queryParameters.containsKey('size')) {
|
||||
final newParams = Map<String, String>.from(uri.queryParameters);
|
||||
newParams['size'] = size.toString();
|
||||
final newUri = uri.replace(queryParameters: newParams);
|
||||
_logger.log('🖼️ Remote mode: adjusted imageproxy size to $size from ${uri.host}');
|
||||
return newUri.toString();
|
||||
}
|
||||
|
||||
// Check if it's from a known CDN
|
||||
for (final domain in externalDomains) {
|
||||
if (uri.host.contains(domain)) {
|
||||
_logger.log('🖼️ Remote mode: using external CDN URL from ${uri.host}');
|
||||
// For Spotify, we can request different sizes
|
||||
if (uri.host.contains('scdn.co') || uri.host.contains('spotifycdn.com')) {
|
||||
// Spotify image URLs can have size in path, but we'll use as-is
|
||||
return path;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if it's an Audiobookshelf URL (cover API endpoint)
|
||||
// Audiobookshelf supports ?width=X parameter for resizing
|
||||
if (uri.path.contains('/api/') && uri.path.contains('/cover')) {
|
||||
final newParams = Map<String, String>.from(uri.queryParameters);
|
||||
newParams['width'] = size.toString();
|
||||
final newUri = uri.replace(queryParameters: newParams);
|
||||
_logger.log('🖼️ Remote mode: adjusted Audiobookshelf cover size to $size from ${uri.host}');
|
||||
return newUri.toString();
|
||||
}
|
||||
|
||||
// Even if not a known CDN, if it's HTTPS it might work
|
||||
_logger.log('🖼️ Remote mode: trying external URL from ${uri.host}');
|
||||
return path;
|
||||
} catch (e) {
|
||||
// Not a valid URL, continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: try any image with a provider that typically has external URLs
|
||||
for (var img in images) {
|
||||
final imgMap = img as Map<String, dynamic>;
|
||||
final provider = imgMap['provider'] as String?;
|
||||
final path = imgMap['path'] as String?;
|
||||
if (path == null) continue;
|
||||
|
||||
// Providers that typically have external URLs in their paths
|
||||
if (provider != null) {
|
||||
if (provider.contains('spotify') ||
|
||||
provider.contains('tidal') ||
|
||||
provider.contains('deezer') ||
|
||||
provider.contains('apple_music') ||
|
||||
provider.contains('musicbrainz')) {
|
||||
if (path.startsWith('https://')) {
|
||||
_logger.log('🖼️ Remote mode: using $provider image URL');
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No external URLs found - images won't load in remote mode for local files
|
||||
_logger.log('🖼️ Remote mode: no external image URL available');
|
||||
return null;
|
||||
}
|
||||
|
||||
// ==================== iTunes Artwork Lookup ====================
|
||||
|
||||
/// Search iTunes for a podcast and return high-res artwork URL
|
||||
@@ -3828,8 +3677,8 @@ class MusicAssistantAPI {
|
||||
/// Cancel all pending requests with an error message
|
||||
void _cancelPendingRequests(String reason) {
|
||||
for (final entry in _pendingRequests.entries) {
|
||||
if (!entry.value.completer.isCompleted) {
|
||||
entry.value.completer.completeError(Exception(reason));
|
||||
if (!entry.value.isCompleted) {
|
||||
entry.value.completeError(Exception(reason));
|
||||
}
|
||||
}
|
||||
_pendingRequests.clear();
|
||||
|
||||
@@ -1,675 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:ensemble/services/remote/webview_webrtc_connection.dart';
|
||||
import 'package:ensemble/services/debug_logger.dart';
|
||||
|
||||
/// Error types for RemoteBridge
|
||||
enum RemoteBridgeErrorType {
|
||||
webrtcConnection,
|
||||
signaling,
|
||||
authentication,
|
||||
dataChannel,
|
||||
timeout,
|
||||
unknown,
|
||||
}
|
||||
|
||||
/// Error information from RemoteBridge
|
||||
class RemoteBridgeError {
|
||||
final RemoteBridgeErrorType type;
|
||||
final String message;
|
||||
final DateTime timestamp;
|
||||
|
||||
RemoteBridgeError({
|
||||
required this.type,
|
||||
required this.message,
|
||||
DateTime? timestamp,
|
||||
}) : timestamp = timestamp ?? DateTime.now();
|
||||
}
|
||||
|
||||
/// Connection state for RemoteBridge
|
||||
enum RemoteBridgeState {
|
||||
disconnected,
|
||||
connecting,
|
||||
authenticating,
|
||||
connected,
|
||||
reconnecting,
|
||||
failed,
|
||||
}
|
||||
|
||||
/// Connection quality metrics
|
||||
class ConnectionMetrics {
|
||||
final int requestsSent;
|
||||
final int responsesReceived;
|
||||
final int reconnectionCount;
|
||||
final Duration? lastLatency;
|
||||
final DateTime? lastActivity;
|
||||
|
||||
ConnectionMetrics({
|
||||
required this.requestsSent,
|
||||
required this.responsesReceived,
|
||||
required this.reconnectionCount,
|
||||
this.lastLatency,
|
||||
this.lastActivity,
|
||||
});
|
||||
|
||||
double get successRate {
|
||||
if (requestsSent == 0) return 1.0;
|
||||
return responsesReceived / requestsSent;
|
||||
}
|
||||
}
|
||||
|
||||
/// A WebRTC-to-WebSocket bridge that allows MusicAssistantAPI to work unchanged
|
||||
/// for remote connections. All traffic is tunneled through a local WebSocket server.
|
||||
///
|
||||
/// Architecture:
|
||||
/// ```
|
||||
/// MusicAssistantAPI → localhost:port → RemoteBridge → WebRTC → MA Server
|
||||
/// Sendspin → localhost:port/sendspin → RemoteBridge → WebRTC (sendspin channel) → MA Server
|
||||
/// ```
|
||||
class RemoteBridge {
|
||||
HttpServer? _server;
|
||||
WebViewWebRTCConnection? _webrtcConnection;
|
||||
int? _port;
|
||||
|
||||
// API client (MusicAssistantAPI)
|
||||
WebSocket? _apiClientSocket;
|
||||
StreamSubscription? _apiClientSubscription;
|
||||
StreamSubscription? _apiWebrtcSubscription;
|
||||
|
||||
// Sendspin client (local player audio)
|
||||
WebSocket? _sendspinClientSocket;
|
||||
StreamSubscription? _sendspinClientSubscription;
|
||||
StreamSubscription? _sendspinTextSubscription;
|
||||
StreamSubscription? _sendspinBinarySubscription;
|
||||
|
||||
Timer? _healthCheckTimer;
|
||||
Timer? _reconnectTimer;
|
||||
|
||||
// Connection parameters for reconnection
|
||||
String? _remoteId;
|
||||
String? _username;
|
||||
String? _password;
|
||||
bool _isReconnecting = false;
|
||||
int _reconnectAttempts = 0;
|
||||
static const int _maxReconnectAttempts = 5;
|
||||
static const Duration _reconnectDelay = Duration(seconds: 3);
|
||||
static const Duration _rateLimitDelay = Duration(seconds: 65);
|
||||
bool _isRateLimited = false;
|
||||
|
||||
// Cached server hello to replay when WS client connects
|
||||
String? _cachedServerHello;
|
||||
|
||||
// Debug counters
|
||||
int _apiMessagesSent = 0;
|
||||
int _apiMessagesReceived = 0;
|
||||
int _sendspinMessagesSent = 0;
|
||||
int _sendspinMessagesReceived = 0;
|
||||
DateTime? _lastMessageReceived;
|
||||
int _totalReconnections = 0;
|
||||
|
||||
// State tracking
|
||||
RemoteBridgeState _state = RemoteBridgeState.disconnected;
|
||||
final _stateController = StreamController<RemoteBridgeState>.broadcast();
|
||||
final _errorController = StreamController<RemoteBridgeError>.broadcast();
|
||||
|
||||
final DebugLogger _logger = DebugLogger();
|
||||
|
||||
int? get port => _port;
|
||||
bool get isRunning => _server != null;
|
||||
bool get isSendspinReady => _webrtcConnection?.isSendspinConnected ?? false;
|
||||
bool get isWebRTCConnected => _webrtcConnection?.isConnected ?? false;
|
||||
RemoteBridgeState get state => _state;
|
||||
Stream<RemoteBridgeState> get stateStream => _stateController.stream;
|
||||
Stream<RemoteBridgeError> get errorStream => _errorController.stream;
|
||||
|
||||
/// Build the hidden WebView widget that must be added to the widget tree.
|
||||
/// This must be called and the returned widget added to the tree BEFORE calling start().
|
||||
/// The WebView is 1x1 pixel and invisible.
|
||||
Widget buildWebView() {
|
||||
// Create the connection if not already created
|
||||
_webrtcConnection ??= WebViewWebRTCConnection();
|
||||
return _webrtcConnection!.buildWebView();
|
||||
}
|
||||
|
||||
/// Get current connection metrics
|
||||
ConnectionMetrics get metrics => ConnectionMetrics(
|
||||
requestsSent: _apiMessagesSent,
|
||||
responsesReceived: _apiMessagesReceived,
|
||||
reconnectionCount: _totalReconnections,
|
||||
lastActivity: _lastMessageReceived,
|
||||
);
|
||||
|
||||
/// Update state and notify listeners
|
||||
void _setState(RemoteBridgeState newState) {
|
||||
if (_state != newState) {
|
||||
_logger.log('RemoteBridge: State changed: $_state -> $newState');
|
||||
_state = newState;
|
||||
_stateController.add(newState);
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit an error to listeners
|
||||
void _emitError(RemoteBridgeErrorType type, String message) {
|
||||
final error = RemoteBridgeError(type: type, message: message);
|
||||
_logger.log('RemoteBridge: Error [$type]: $message');
|
||||
_errorController.add(error);
|
||||
}
|
||||
|
||||
/// Start the bridge and connect to the remote MA server.
|
||||
/// Returns the local port number to connect to, or null if failed.
|
||||
Future<int?> start(String remoteId, String username, String password) async {
|
||||
_logger.log('RemoteBridge: Starting bridge for remote ID: $remoteId');
|
||||
_setState(RemoteBridgeState.connecting);
|
||||
|
||||
// Store connection parameters for reconnection
|
||||
_remoteId = remoteId;
|
||||
_username = username;
|
||||
_password = password;
|
||||
_reconnectAttempts = 0;
|
||||
|
||||
try {
|
||||
// Step 1: Connect to MA via WebRTC (using WebView-based implementation)
|
||||
// The WebView must be in the widget tree first - call buildWebView() before start()
|
||||
_webrtcConnection ??= WebViewWebRTCConnection();
|
||||
|
||||
_webrtcConnection!.onStateChanged = (state) {
|
||||
_logger.log('RemoteBridge: WebRTC state: $state');
|
||||
if (state == WebViewWebRTCConnectionState.disconnected ||
|
||||
state == WebViewWebRTCConnectionState.failed) {
|
||||
_handleWebRTCDisconnection();
|
||||
}
|
||||
};
|
||||
|
||||
_webrtcConnection!.onError = (error) {
|
||||
_logger.log('RemoteBridge: WebRTC error: $error');
|
||||
_emitError(RemoteBridgeErrorType.webrtcConnection, error);
|
||||
};
|
||||
|
||||
final connected = await _webrtcConnection!.connect(remoteId);
|
||||
if (!connected) {
|
||||
_logger.log('RemoteBridge: WebRTC connection failed');
|
||||
_setState(RemoteBridgeState.failed);
|
||||
_emitError(RemoteBridgeErrorType.webrtcConnection, 'Failed to connect to remote server');
|
||||
await stop();
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.log('RemoteBridge: WebRTC connected, authenticating...');
|
||||
_setState(RemoteBridgeState.authenticating);
|
||||
|
||||
// Step 2: Authenticate with MA
|
||||
final authenticated = await _authenticate(username, password);
|
||||
if (!authenticated) {
|
||||
_logger.log('RemoteBridge: Authentication failed');
|
||||
_setState(RemoteBridgeState.failed);
|
||||
_emitError(RemoteBridgeErrorType.authentication, 'Authentication failed');
|
||||
await stop();
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.log('RemoteBridge: Authentication successful');
|
||||
_setState(RemoteBridgeState.connected);
|
||||
|
||||
// Step 3: Cache the server hello (it was already received by WebRTCConnection)
|
||||
if (_webrtcConnection!.serverInfo != null) {
|
||||
_cachedServerHello = jsonEncode(_webrtcConnection!.serverInfo);
|
||||
_logger.log('RemoteBridge: Cached server hello');
|
||||
}
|
||||
|
||||
// Step 4: Start local WebSocket server
|
||||
_server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
_port = _server!.port;
|
||||
_logger.log('RemoteBridge: Local WS server started on port $_port');
|
||||
|
||||
// Handle incoming connections
|
||||
_server!.listen(_handleHttpRequest);
|
||||
|
||||
// Step 5: Subscribe to WebRTC API messages to forward to API client
|
||||
_apiWebrtcSubscription = _webrtcConnection!.rawMessages.listen((message) {
|
||||
_apiMessagesReceived++;
|
||||
_lastMessageReceived = DateTime.now();
|
||||
if (_apiClientSocket != null) {
|
||||
_apiClientSocket!.add(message);
|
||||
}
|
||||
});
|
||||
|
||||
// Step 6: Subscribe to Sendspin WebRTC messages (text) to forward to Sendspin client
|
||||
_sendspinTextSubscription = _webrtcConnection!.sendspinTextMessages.listen((message) {
|
||||
_sendspinMessagesReceived++;
|
||||
_lastMessageReceived = DateTime.now();
|
||||
if (_sendspinClientSocket != null) {
|
||||
_sendspinClientSocket!.add(message);
|
||||
}
|
||||
});
|
||||
|
||||
// Step 7: Subscribe to Sendspin WebRTC messages (binary audio) to forward to Sendspin client
|
||||
_sendspinBinarySubscription = _webrtcConnection!.sendspinBinaryMessages.listen((data) {
|
||||
_sendspinMessagesReceived++;
|
||||
if (_sendspinClientSocket != null) {
|
||||
// Forward binary audio data to Sendspin client
|
||||
_sendspinClientSocket!.add(data);
|
||||
}
|
||||
});
|
||||
|
||||
// Step 8: Start health check timer
|
||||
_startHealthCheck();
|
||||
|
||||
return _port;
|
||||
} catch (e) {
|
||||
_logger.log('RemoteBridge: Start failed: $e');
|
||||
_setState(RemoteBridgeState.failed);
|
||||
_emitError(RemoteBridgeErrorType.unknown, e.toString());
|
||||
await stop();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Authenticate with the MA server over WebRTC.
|
||||
Future<bool> _authenticate(String username, String password) async {
|
||||
try {
|
||||
// Step 1: Login to get access token
|
||||
_logger.log('RemoteBridge: Sending auth/login...');
|
||||
final loginResult = await _webrtcConnection!.sendRequest('auth/login', {
|
||||
'username': username,
|
||||
'password': password,
|
||||
'device_name': 'Ensemble Mobile App',
|
||||
});
|
||||
|
||||
_logger.log('RemoteBridge: Login result: $loginResult');
|
||||
|
||||
// Check for error response
|
||||
if (loginResult.containsKey('error_code')) {
|
||||
_logger.log('RemoteBridge: Login error: ${loginResult['details']}');
|
||||
return false;
|
||||
}
|
||||
|
||||
String? accessToken;
|
||||
if (loginResult['result'] != null) {
|
||||
final result = loginResult['result'];
|
||||
if (result is Map<String, dynamic>) {
|
||||
if (result['success'] == true) {
|
||||
accessToken = result['access_token'] as String?;
|
||||
final user = result['user'] as Map<String, dynamic>?;
|
||||
_logger.log('RemoteBridge: Login successful! User: ${user?['username']}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (accessToken == null) {
|
||||
_logger.log('RemoteBridge: No access token received');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Step 2: Authenticate the session with the token
|
||||
_logger.log('RemoteBridge: Authenticating session with token...');
|
||||
final authResult = await _webrtcConnection!.sendRequest('auth', {
|
||||
'token': accessToken,
|
||||
});
|
||||
|
||||
_logger.log('RemoteBridge: Auth result: $authResult');
|
||||
|
||||
if (authResult.containsKey('error_code')) {
|
||||
_logger.log('RemoteBridge: Session auth failed: ${authResult['details']}');
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.log('RemoteBridge: Session authenticated successfully!');
|
||||
return true;
|
||||
} catch (e) {
|
||||
_logger.log('RemoteBridge: Auth error: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle incoming HTTP requests and upgrade to WebSocket.
|
||||
void _handleHttpRequest(HttpRequest request) async {
|
||||
final path = request.uri.path;
|
||||
_logger.log('RemoteBridge: Incoming HTTP request: $path');
|
||||
|
||||
if (WebSocketTransformer.isUpgradeRequest(request)) {
|
||||
try {
|
||||
final socket = await WebSocketTransformer.upgrade(request);
|
||||
|
||||
// Route based on path: /sendspin for audio, anything else for API
|
||||
if (path == '/sendspin') {
|
||||
_handleSendspinConnection(socket);
|
||||
} else {
|
||||
_handleApiConnection(socket);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('RemoteBridge: WebSocket upgrade failed: $e');
|
||||
request.response.statusCode = HttpStatus.internalServerError;
|
||||
await request.response.close();
|
||||
}
|
||||
} else {
|
||||
// Not a WebSocket request
|
||||
request.response.statusCode = HttpStatus.badRequest;
|
||||
await request.response.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a new API WebSocket client connection.
|
||||
void _handleApiConnection(WebSocket socket) {
|
||||
_logger.log('RemoteBridge: API client connected');
|
||||
|
||||
// Only allow one API client at a time
|
||||
if (_apiClientSocket != null) {
|
||||
_logger.log('RemoteBridge: Closing existing API client connection');
|
||||
_apiClientSubscription?.cancel();
|
||||
_apiClientSocket?.close();
|
||||
}
|
||||
|
||||
_apiClientSocket = socket;
|
||||
|
||||
// Step 1: Send cached server hello immediately
|
||||
if (_cachedServerHello != null) {
|
||||
_logger.log('RemoteBridge: Sending cached server hello to API client');
|
||||
_apiClientSocket!.add(_cachedServerHello!);
|
||||
}
|
||||
|
||||
// Step 2: Forward all messages from API client to WebRTC (ma-api channel)
|
||||
_apiClientSubscription = _apiClientSocket!.listen(
|
||||
(message) {
|
||||
if (message is String && _webrtcConnection != null) {
|
||||
_apiMessagesSent++;
|
||||
_webrtcConnection!.sendRaw(message);
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
_logger.log('RemoteBridge: API client disconnected');
|
||||
_apiClientSocket = null;
|
||||
_apiClientSubscription = null;
|
||||
},
|
||||
onError: (error) {
|
||||
_logger.log('RemoteBridge: API client error: $error');
|
||||
_apiClientSocket = null;
|
||||
_apiClientSubscription = null;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Handle a new Sendspin WebSocket client connection (for audio streaming).
|
||||
void _handleSendspinConnection(WebSocket socket) {
|
||||
_logger.log('RemoteBridge: Sendspin client connected');
|
||||
|
||||
// Only allow one Sendspin client at a time
|
||||
if (_sendspinClientSocket != null) {
|
||||
_logger.log('RemoteBridge: Closing existing Sendspin client connection');
|
||||
_sendspinClientSubscription?.cancel();
|
||||
_sendspinClientSocket?.close();
|
||||
}
|
||||
|
||||
_sendspinClientSocket = socket;
|
||||
|
||||
// Forward all messages from Sendspin client to WebRTC (sendspin channel)
|
||||
_sendspinClientSubscription = _sendspinClientSocket!.listen(
|
||||
(message) {
|
||||
if (_webrtcConnection != null) {
|
||||
_sendspinMessagesSent++;
|
||||
if (message is String) {
|
||||
// Text message (JSON control)
|
||||
_webrtcConnection!.sendSendspinText(message);
|
||||
} else if (message is List<int>) {
|
||||
// Binary message (would be audio data from client, unlikely but handle it)
|
||||
_webrtcConnection!.sendSendspinBinary(Uint8List.fromList(message));
|
||||
}
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
_logger.log('RemoteBridge: Sendspin client disconnected');
|
||||
_sendspinClientSocket = null;
|
||||
_sendspinClientSubscription = null;
|
||||
},
|
||||
onError: (error) {
|
||||
_logger.log('RemoteBridge: Sendspin client error: $error');
|
||||
_sendspinClientSocket = null;
|
||||
_sendspinClientSubscription = null;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Handle WebRTC disconnection - attempt reconnection.
|
||||
void _handleWebRTCDisconnection() {
|
||||
_logger.log('RemoteBridge: WebRTC disconnected');
|
||||
|
||||
// Don't close WS clients immediately - they will reconnect when WebRTC is back
|
||||
// Instead, attempt to reconnect WebRTC
|
||||
_scheduleReconnect();
|
||||
}
|
||||
|
||||
/// Schedule a WebRTC reconnection attempt.
|
||||
void _scheduleReconnect() {
|
||||
if (_isReconnecting) {
|
||||
_logger.log('RemoteBridge: Already reconnecting, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
if (_remoteId == null || _username == null || _password == null) {
|
||||
_logger.log('RemoteBridge: No connection parameters, cannot reconnect');
|
||||
_setState(RemoteBridgeState.failed);
|
||||
_emitError(RemoteBridgeErrorType.webrtcConnection, 'Cannot reconnect - no connection parameters');
|
||||
_closeAllClients();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_reconnectAttempts >= _maxReconnectAttempts) {
|
||||
_logger.log('RemoteBridge: Max reconnect attempts reached, giving up');
|
||||
_setState(RemoteBridgeState.failed);
|
||||
_emitError(RemoteBridgeErrorType.webrtcConnection, 'Max reconnection attempts reached');
|
||||
_closeAllClients();
|
||||
return;
|
||||
}
|
||||
|
||||
_setState(RemoteBridgeState.reconnecting);
|
||||
_reconnectAttempts++;
|
||||
_totalReconnections++;
|
||||
|
||||
// Use longer delay if rate limited, otherwise exponential backoff
|
||||
final Duration delay;
|
||||
if (_isRateLimited) {
|
||||
delay = _rateLimitDelay;
|
||||
_logger.log('RemoteBridge: Rate limited - waiting ${delay.inSeconds}s before reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts');
|
||||
} else {
|
||||
delay = _reconnectDelay * _reconnectAttempts;
|
||||
_logger.log('RemoteBridge: Scheduling reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts in ${delay.inSeconds}s');
|
||||
}
|
||||
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = Timer(delay, _reconnectWebRTC);
|
||||
}
|
||||
|
||||
/// Attempt to reconnect WebRTC.
|
||||
Future<void> _reconnectWebRTC() async {
|
||||
if (_isReconnecting) return;
|
||||
_isReconnecting = true;
|
||||
|
||||
_logger.log('RemoteBridge: Attempting WebRTC reconnection...');
|
||||
|
||||
try {
|
||||
// Clean up subscriptions but keep the WebView connection (it's still in the widget tree)
|
||||
_apiWebrtcSubscription?.cancel();
|
||||
_sendspinTextSubscription?.cancel();
|
||||
_sendspinBinarySubscription?.cancel();
|
||||
await _webrtcConnection?.disconnect();
|
||||
|
||||
// Reuse existing WebView connection (WebView is already in widget tree)
|
||||
// If somehow null, create a new one (shouldn't happen in normal flow)
|
||||
_webrtcConnection ??= WebViewWebRTCConnection();
|
||||
|
||||
_webrtcConnection!.onStateChanged = (state) {
|
||||
_logger.log('RemoteBridge: WebRTC state (reconnect): $state');
|
||||
if (state == WebViewWebRTCConnectionState.disconnected ||
|
||||
state == WebViewWebRTCConnectionState.failed) {
|
||||
_isReconnecting = false;
|
||||
_handleWebRTCDisconnection();
|
||||
} else if (state == WebViewWebRTCConnectionState.connected) {
|
||||
_reconnectAttempts = 0; // Reset on successful connection
|
||||
}
|
||||
};
|
||||
|
||||
_webrtcConnection!.onError = (error) {
|
||||
_logger.log('RemoteBridge: WebRTC error (reconnect): $error');
|
||||
// Detect rate limiting from signaling server
|
||||
if (error.toLowerCase().contains('rate limit')) {
|
||||
_logger.log('RemoteBridge: Rate limited - will wait ${_rateLimitDelay.inSeconds}s before retry');
|
||||
_isRateLimited = true;
|
||||
}
|
||||
};
|
||||
|
||||
final connected = await _webrtcConnection!.connect(_remoteId!);
|
||||
if (!connected) {
|
||||
_logger.log('RemoteBridge: WebRTC reconnection failed');
|
||||
_isReconnecting = false;
|
||||
_scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.log('RemoteBridge: WebRTC reconnected, re-authenticating...');
|
||||
|
||||
// Re-authenticate
|
||||
final authenticated = await _authenticate(_username!, _password!);
|
||||
if (!authenticated) {
|
||||
_logger.log('RemoteBridge: Re-authentication failed');
|
||||
_isReconnecting = false;
|
||||
_scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.log('RemoteBridge: Re-authentication successful');
|
||||
|
||||
// Re-cache server hello
|
||||
if (_webrtcConnection!.serverInfo != null) {
|
||||
_cachedServerHello = jsonEncode(_webrtcConnection!.serverInfo);
|
||||
_logger.log('RemoteBridge: Re-cached server hello');
|
||||
}
|
||||
|
||||
// Re-subscribe to WebRTC streams
|
||||
_apiWebrtcSubscription = _webrtcConnection!.rawMessages.listen((message) {
|
||||
_apiMessagesReceived++;
|
||||
_lastMessageReceived = DateTime.now();
|
||||
if (_apiClientSocket != null) {
|
||||
_apiClientSocket!.add(message);
|
||||
}
|
||||
});
|
||||
|
||||
_sendspinTextSubscription = _webrtcConnection!.sendspinTextMessages.listen((message) {
|
||||
_sendspinMessagesReceived++;
|
||||
_lastMessageReceived = DateTime.now();
|
||||
if (_sendspinClientSocket != null) {
|
||||
_sendspinClientSocket!.add(message);
|
||||
}
|
||||
});
|
||||
|
||||
_sendspinBinarySubscription = _webrtcConnection!.sendspinBinaryMessages.listen((data) {
|
||||
_sendspinMessagesReceived++;
|
||||
if (_sendspinClientSocket != null) {
|
||||
_sendspinClientSocket!.add(data);
|
||||
}
|
||||
});
|
||||
|
||||
_logger.log('RemoteBridge: ✅ WebRTC reconnection complete');
|
||||
_setState(RemoteBridgeState.connected);
|
||||
_isReconnecting = false;
|
||||
_reconnectAttempts = 0;
|
||||
_isRateLimited = false;
|
||||
} catch (e) {
|
||||
_logger.log('RemoteBridge: Reconnection error: $e');
|
||||
_emitError(RemoteBridgeErrorType.webrtcConnection, e.toString());
|
||||
_isReconnecting = false;
|
||||
_scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/// Close all WS clients (called when giving up on reconnection).
|
||||
void _closeAllClients() {
|
||||
_logger.log('RemoteBridge: Closing all WS clients');
|
||||
|
||||
_apiClientSocket?.close();
|
||||
_apiClientSocket = null;
|
||||
_apiClientSubscription?.cancel();
|
||||
_apiClientSubscription = null;
|
||||
|
||||
_sendspinClientSocket?.close();
|
||||
_sendspinClientSocket = null;
|
||||
_sendspinClientSubscription?.cancel();
|
||||
_sendspinClientSubscription = null;
|
||||
}
|
||||
|
||||
/// Start periodic health check to monitor connection state
|
||||
void _startHealthCheck() {
|
||||
_healthCheckTimer?.cancel();
|
||||
_healthCheckTimer = Timer.periodic(const Duration(seconds: 10), (_) {
|
||||
final dcState = _webrtcConnection?.dataChannelStateDebug ?? 'no connection';
|
||||
final sendspinState = _webrtcConnection?.isSendspinConnected ?? false;
|
||||
final wcState = _webrtcConnection?.state.toString() ?? 'no connection';
|
||||
final timeSinceLastMsg = _lastMessageReceived != null
|
||||
? DateTime.now().difference(_lastMessageReceived!).inSeconds
|
||||
: -1;
|
||||
_logger.log('RemoteBridge: Health check - API DC:$dcState, Sendspin:$sendspinState, WC:$wcState, '
|
||||
'API sent:$_apiMessagesSent recv:$_apiMessagesReceived, '
|
||||
'Sendspin sent:$_sendspinMessagesSent recv:$_sendspinMessagesReceived, '
|
||||
'lastRecv:${timeSinceLastMsg}s ago');
|
||||
});
|
||||
}
|
||||
|
||||
/// Stop the bridge and disconnect from the remote server.
|
||||
Future<void> stop() async {
|
||||
_logger.log('RemoteBridge: Stopping bridge');
|
||||
_setState(RemoteBridgeState.disconnected);
|
||||
|
||||
// Cancel reconnection
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = null;
|
||||
_isReconnecting = false;
|
||||
_reconnectAttempts = 0;
|
||||
|
||||
_healthCheckTimer?.cancel();
|
||||
_healthCheckTimer = null;
|
||||
|
||||
// Cancel API subscriptions
|
||||
_apiClientSubscription?.cancel();
|
||||
_apiClientSubscription = null;
|
||||
_apiWebrtcSubscription?.cancel();
|
||||
_apiWebrtcSubscription = null;
|
||||
|
||||
// Cancel Sendspin subscriptions
|
||||
_sendspinClientSubscription?.cancel();
|
||||
_sendspinClientSubscription = null;
|
||||
_sendspinTextSubscription?.cancel();
|
||||
_sendspinTextSubscription = null;
|
||||
_sendspinBinarySubscription?.cancel();
|
||||
_sendspinBinarySubscription = null;
|
||||
|
||||
// Close client sockets
|
||||
await _apiClientSocket?.close();
|
||||
_apiClientSocket = null;
|
||||
await _sendspinClientSocket?.close();
|
||||
_sendspinClientSocket = null;
|
||||
|
||||
await _server?.close(force: true);
|
||||
_server = null;
|
||||
_port = null;
|
||||
|
||||
await _webrtcConnection?.disconnect();
|
||||
_webrtcConnection = null;
|
||||
|
||||
_cachedServerHello = null;
|
||||
|
||||
// Clear connection parameters
|
||||
_remoteId = null;
|
||||
_username = null;
|
||||
_password = null;
|
||||
|
||||
_logger.log('RemoteBridge: Bridge stopped');
|
||||
}
|
||||
|
||||
/// Dispose the bridge and close all stream controllers.
|
||||
void dispose() {
|
||||
stop();
|
||||
_stateController.close();
|
||||
_errorController.close();
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'package:ensemble/services/remote/webrtc_connection.dart';
|
||||
import 'package:ensemble/services/debug_logger.dart';
|
||||
|
||||
/// Manages remote connections to MA servers via WebRTC
|
||||
class RemoteConnectionManager {
|
||||
final WebRTCConnection _connection = WebRTCConnection();
|
||||
|
||||
StreamSubscription? _messageSubscription;
|
||||
final _eventController = StreamController<Map<String, dynamic>>.broadcast();
|
||||
|
||||
bool _isAuthenticated = false;
|
||||
String? _serverVersion;
|
||||
|
||||
// Callbacks
|
||||
Function(bool connected)? onConnectionChanged;
|
||||
Function(String error)? onError;
|
||||
|
||||
bool get isConnected => _connection.isConnected && _isAuthenticated;
|
||||
Stream<Map<String, dynamic>> get events => _eventController.stream;
|
||||
String? get serverVersion => _serverVersion;
|
||||
|
||||
RemoteConnectionManager() {
|
||||
_connection.onStateChanged = _onConnectionStateChanged;
|
||||
_connection.onError = (error) => onError?.call(error);
|
||||
|
||||
// Forward events from the data channel
|
||||
_messageSubscription = _connection.messages.listen((message) {
|
||||
// Check if this is an event (has 'event' key)
|
||||
if (message.containsKey('event')) {
|
||||
_eventController.add(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Connect to a remote MA server using Remote Access ID
|
||||
Future<bool> connect(String remoteId, String username, String password) async {
|
||||
DebugLogger().log('RemoteConnection: Connecting to remote ID: $remoteId');
|
||||
|
||||
// Connect WebRTC
|
||||
final connected = await _connection.connect(remoteId);
|
||||
if (!connected) {
|
||||
DebugLogger().log('RemoteConnection: WebRTC connection failed');
|
||||
return false;
|
||||
}
|
||||
|
||||
DebugLogger().log('RemoteConnection: WebRTC connected, authenticating...');
|
||||
|
||||
// Authenticate with MA
|
||||
try {
|
||||
final authenticated = await _authenticate(username, password);
|
||||
if (!authenticated) {
|
||||
DebugLogger().log('RemoteConnection: Authentication failed');
|
||||
await _connection.disconnect();
|
||||
return false;
|
||||
}
|
||||
|
||||
_isAuthenticated = true;
|
||||
DebugLogger().log('RemoteConnection: Fully connected and authenticated');
|
||||
onConnectionChanged?.call(true);
|
||||
return true;
|
||||
} catch (e) {
|
||||
DebugLogger().log('RemoteConnection: Auth error: $e');
|
||||
await _connection.disconnect();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Authenticate with the MA server
|
||||
Future<bool> _authenticate(String username, String password) async {
|
||||
try {
|
||||
// Step 1: Login to get access token
|
||||
DebugLogger().log('RemoteConnection: Sending auth/login...');
|
||||
final loginResult = await _connection.sendRequest('auth/login', {
|
||||
'username': username,
|
||||
'password': password,
|
||||
'device_name': 'Ensemble Mobile App',
|
||||
});
|
||||
|
||||
DebugLogger().log('RemoteConnection: Login result: $loginResult');
|
||||
|
||||
// Check for error response
|
||||
if (loginResult.containsKey('error_code')) {
|
||||
DebugLogger().log('RemoteConnection: Login error: ${loginResult['details']}');
|
||||
return false;
|
||||
}
|
||||
|
||||
String? accessToken;
|
||||
if (loginResult['result'] != null) {
|
||||
final result = loginResult['result'];
|
||||
|
||||
if (result is Map<String, dynamic>) {
|
||||
if (result['success'] == true) {
|
||||
accessToken = result['access_token'] as String?;
|
||||
final user = result['user'] as Map<String, dynamic>?;
|
||||
|
||||
DebugLogger().log('RemoteConnection: Login successful!');
|
||||
DebugLogger().log('RemoteConnection: User: ${user?['username']} (${user?['role']})');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (accessToken == null) {
|
||||
DebugLogger().log('RemoteConnection: No access token received');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Step 2: Authenticate the session with the token
|
||||
DebugLogger().log('RemoteConnection: Authenticating session with token...');
|
||||
final authResult = await _connection.sendRequest('auth', {
|
||||
'token': accessToken,
|
||||
});
|
||||
|
||||
DebugLogger().log('RemoteConnection: Auth result: $authResult');
|
||||
|
||||
if (authResult.containsKey('error_code')) {
|
||||
DebugLogger().log('RemoteConnection: Session auth failed: ${authResult['details']}');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store the token for later use
|
||||
_accessToken = accessToken;
|
||||
DebugLogger().log('RemoteConnection: Session authenticated successfully!');
|
||||
return true;
|
||||
} catch (e) {
|
||||
DebugLogger().log('RemoteConnection: Login error: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String? _accessToken;
|
||||
|
||||
/// Send a command to the MA server
|
||||
Future<Map<String, dynamic>> sendCommand(
|
||||
String command, [
|
||||
Map<String, dynamic>? params,
|
||||
]) async {
|
||||
if (!_connection.isConnected) {
|
||||
throw Exception('Not connected');
|
||||
}
|
||||
|
||||
return await _connection.sendRequest(command, params);
|
||||
}
|
||||
|
||||
/// Subscribe to events from the server
|
||||
Future<void> subscribe(List<String> eventTypes) async {
|
||||
await sendCommand('subscribe_events', {
|
||||
'event_types': eventTypes,
|
||||
});
|
||||
}
|
||||
|
||||
/// Disconnect from the remote server
|
||||
Future<void> disconnect() async {
|
||||
_isAuthenticated = false;
|
||||
await _connection.disconnect();
|
||||
onConnectionChanged?.call(false);
|
||||
}
|
||||
|
||||
void _onConnectionStateChanged(WebRTCConnectionState state) {
|
||||
DebugLogger().log('RemoteConnection: State changed to $state');
|
||||
|
||||
if (state == WebRTCConnectionState.disconnected ||
|
||||
state == WebRTCConnectionState.failed) {
|
||||
_isAuthenticated = false;
|
||||
onConnectionChanged?.call(false);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_messageSubscription?.cancel();
|
||||
_eventController.close();
|
||||
_connection.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import 'package:ensemble/services/debug_logger.dart';
|
||||
|
||||
/// Message types for the MA signaling protocol
|
||||
class SignalingMessageType {
|
||||
static const String ping = 'ping';
|
||||
static const String pong = 'pong';
|
||||
static const String connectRequest = 'connect-request';
|
||||
static const String connected = 'connected';
|
||||
static const String offer = 'offer';
|
||||
static const String answer = 'answer';
|
||||
static const String iceCandidate = 'ice-candidate';
|
||||
static const String peerDisconnected = 'peer-disconnected';
|
||||
static const String error = 'error';
|
||||
}
|
||||
|
||||
/// ICE server configuration from signaling
|
||||
class IceServer {
|
||||
final List<String> urls;
|
||||
final String? username;
|
||||
final String? credential;
|
||||
|
||||
IceServer({
|
||||
required this.urls,
|
||||
this.username,
|
||||
this.credential,
|
||||
});
|
||||
|
||||
factory IceServer.fromJson(Map<String, dynamic> json) {
|
||||
// Handle urls as either String or List<String>
|
||||
final urlsRaw = json['urls'];
|
||||
final List<String> urls;
|
||||
if (urlsRaw is String) {
|
||||
urls = [urlsRaw];
|
||||
} else if (urlsRaw is List) {
|
||||
urls = urlsRaw.cast<String>();
|
||||
} else {
|
||||
urls = [];
|
||||
}
|
||||
|
||||
return IceServer(
|
||||
urls: urls,
|
||||
username: json['username'] as String?,
|
||||
credential: json['credential'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toWebRtcConfig() {
|
||||
final config = <String, dynamic>{'urls': urls};
|
||||
if (username != null) config['username'] = username;
|
||||
if (credential != null) config['credential'] = credential;
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
/// Client for connecting to the MA signaling server
|
||||
class SignalingClient {
|
||||
static const String _signalingUrl = 'wss://signaling.music-assistant.io/ws';
|
||||
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription? _subscription;
|
||||
Timer? _pingTimer;
|
||||
|
||||
String? _sessionId;
|
||||
String? _remoteId;
|
||||
List<IceServer> _iceServers = [];
|
||||
bool _isConnected = false;
|
||||
|
||||
// Callbacks
|
||||
Function(String sessionId, List<IceServer> iceServers)? onConnected;
|
||||
Function(Map<String, dynamic> answer)? onAnswer;
|
||||
Function(Map<String, dynamic> candidate)? onIceCandidate;
|
||||
Function(String error)? onError;
|
||||
Function()? onPeerDisconnected;
|
||||
Function()? onDisconnected;
|
||||
|
||||
String? get sessionId => _sessionId;
|
||||
List<IceServer> get iceServers => _iceServers;
|
||||
bool get isConnected => _isConnected;
|
||||
|
||||
/// Connect to the signaling server and request connection to a remote MA server
|
||||
Future<bool> connect(String remoteId) async {
|
||||
DebugLogger().log('Signaling: Connecting to $_signalingUrl');
|
||||
|
||||
try {
|
||||
// Normalize remote ID (remove dashes, uppercase)
|
||||
final normalizedId = remoteId.replaceAll('-', '').toUpperCase();
|
||||
_remoteId = normalizedId;
|
||||
DebugLogger().log('Signaling: Remote ID: $normalizedId');
|
||||
|
||||
_channel = WebSocketChannel.connect(Uri.parse(_signalingUrl));
|
||||
await _channel!.ready;
|
||||
|
||||
_subscription = _channel!.stream.listen(
|
||||
_handleMessage,
|
||||
onError: (error) {
|
||||
DebugLogger().log('Signaling: WebSocket error: $error');
|
||||
onError?.call(error.toString());
|
||||
_cleanup();
|
||||
},
|
||||
onDone: () {
|
||||
DebugLogger().log('Signaling: WebSocket closed');
|
||||
onDisconnected?.call();
|
||||
_cleanup();
|
||||
},
|
||||
);
|
||||
|
||||
// Start ping timer to keep connection alive
|
||||
_startPingTimer();
|
||||
|
||||
// Send connect request
|
||||
_send({
|
||||
'type': SignalingMessageType.connectRequest,
|
||||
'remoteId': normalizedId,
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
DebugLogger().log('Signaling: Failed to connect: $e');
|
||||
onError?.call(e.toString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Send WebRTC offer to the remote server
|
||||
void sendOffer(Map<String, dynamic> offer) {
|
||||
if (_sessionId == null || _remoteId == null) {
|
||||
DebugLogger().log('Signaling: Cannot send offer - no session');
|
||||
return;
|
||||
}
|
||||
|
||||
_send({
|
||||
'type': SignalingMessageType.offer,
|
||||
'remoteId': _remoteId,
|
||||
'sessionId': _sessionId,
|
||||
'data': offer,
|
||||
});
|
||||
}
|
||||
|
||||
/// Send ICE candidate to the remote server
|
||||
void sendIceCandidate(Map<String, dynamic> candidate) {
|
||||
if (_sessionId == null || _remoteId == null) {
|
||||
DebugLogger().log('Signaling: Cannot send ICE candidate - no session');
|
||||
return;
|
||||
}
|
||||
|
||||
_send({
|
||||
'type': SignalingMessageType.iceCandidate,
|
||||
'remoteId': _remoteId,
|
||||
'sessionId': _sessionId,
|
||||
'data': candidate,
|
||||
});
|
||||
}
|
||||
|
||||
/// Disconnect from the signaling server
|
||||
void disconnect() {
|
||||
DebugLogger().log('Signaling: Disconnecting');
|
||||
_cleanup();
|
||||
}
|
||||
|
||||
void _handleMessage(dynamic data) {
|
||||
try {
|
||||
final message = jsonDecode(data as String) as Map<String, dynamic>;
|
||||
final type = message['type'] as String?;
|
||||
|
||||
DebugLogger().log('Signaling: Received message type: $type');
|
||||
|
||||
switch (type) {
|
||||
case SignalingMessageType.ping:
|
||||
// Server is pinging us - respond with pong to keep connection alive
|
||||
_send({'type': SignalingMessageType.pong});
|
||||
break;
|
||||
|
||||
case SignalingMessageType.pong:
|
||||
// Ignore pong responses to our pings
|
||||
break;
|
||||
|
||||
case SignalingMessageType.connected:
|
||||
_handleConnected(message);
|
||||
break;
|
||||
|
||||
case SignalingMessageType.answer:
|
||||
_handleAnswer(message);
|
||||
break;
|
||||
|
||||
case SignalingMessageType.iceCandidate:
|
||||
_handleIceCandidate(message);
|
||||
break;
|
||||
|
||||
case SignalingMessageType.peerDisconnected:
|
||||
DebugLogger().log('Signaling: Peer disconnected');
|
||||
onPeerDisconnected?.call();
|
||||
break;
|
||||
|
||||
case SignalingMessageType.error:
|
||||
final error = message['error'] as String? ?? 'Unknown error';
|
||||
DebugLogger().log('Signaling: Error from server: $error');
|
||||
onError?.call(error);
|
||||
break;
|
||||
|
||||
default:
|
||||
DebugLogger().log('Signaling: Unknown message type: $type');
|
||||
}
|
||||
} catch (e) {
|
||||
DebugLogger().log('Signaling: Failed to handle message: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _handleConnected(Map<String, dynamic> message) {
|
||||
_sessionId = message['sessionId'] as String?;
|
||||
_isConnected = true;
|
||||
|
||||
// Parse ICE servers
|
||||
final iceServersJson = message['iceServers'] as List<dynamic>?;
|
||||
if (iceServersJson != null) {
|
||||
_iceServers = iceServersJson
|
||||
.map((s) => IceServer.fromJson(s as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
DebugLogger().log('Signaling: Connected with session $_sessionId');
|
||||
DebugLogger().log('Signaling: Received ${_iceServers.length} ICE servers');
|
||||
|
||||
onConnected?.call(_sessionId!, _iceServers);
|
||||
}
|
||||
|
||||
void _handleAnswer(Map<String, dynamic> message) {
|
||||
final answer = message['data'] as Map<String, dynamic>?;
|
||||
if (answer != null) {
|
||||
DebugLogger().log('Signaling: Received answer');
|
||||
onAnswer?.call(answer);
|
||||
}
|
||||
}
|
||||
|
||||
void _handleIceCandidate(Map<String, dynamic> message) {
|
||||
final candidate = message['data'] as Map<String, dynamic>?;
|
||||
if (candidate != null) {
|
||||
DebugLogger().log('Signaling: Received ICE candidate');
|
||||
onIceCandidate?.call(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
void _send(Map<String, dynamic> message) {
|
||||
if (_channel == null) return;
|
||||
|
||||
final json = jsonEncode(message);
|
||||
DebugLogger().log('Signaling: Sending ${message['type']}');
|
||||
_channel!.sink.add(json);
|
||||
}
|
||||
|
||||
void _startPingTimer() {
|
||||
_pingTimer?.cancel();
|
||||
// Send ping every 15 seconds to keep connection alive
|
||||
_pingTimer = Timer.periodic(const Duration(seconds: 15), (_) {
|
||||
_send({'type': SignalingMessageType.ping});
|
||||
});
|
||||
}
|
||||
|
||||
void _cleanup() {
|
||||
_pingTimer?.cancel();
|
||||
_pingTimer = null;
|
||||
_subscription?.cancel();
|
||||
_subscription = null;
|
||||
_channel?.sink.close();
|
||||
_channel = null;
|
||||
_sessionId = null;
|
||||
_remoteId = null;
|
||||
_isConnected = false;
|
||||
}
|
||||
}
|
||||
@@ -1,506 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter_webrtc/flutter_webrtc.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:ensemble/services/remote/signaling_client.dart';
|
||||
import 'package:ensemble/services/debug_logger.dart';
|
||||
|
||||
/// WebRTC connection state
|
||||
enum WebRTCConnectionState {
|
||||
disconnected,
|
||||
connecting,
|
||||
connected,
|
||||
failed,
|
||||
}
|
||||
|
||||
/// Manages a WebRTC peer connection for remote MA access
|
||||
class WebRTCConnection {
|
||||
RTCPeerConnection? _peerConnection;
|
||||
RTCDataChannel? _dataChannel;
|
||||
RTCDataChannel? _sendspinDataChannel;
|
||||
final SignalingClient _signalingClient = SignalingClient();
|
||||
final _uuid = const Uuid();
|
||||
|
||||
WebRTCConnectionState _state = WebRTCConnectionState.disconnected;
|
||||
Completer<bool>? _connectionCompleter;
|
||||
bool _serverHelloReceived = false;
|
||||
Completer<void>? _serverHelloCompleter;
|
||||
|
||||
// Message handling for MA API
|
||||
final _messageController = StreamController<Map<String, dynamic>>.broadcast();
|
||||
final _rawMessageController = StreamController<String>.broadcast();
|
||||
final Map<String, Completer<Map<String, dynamic>>> _pendingRequests = {};
|
||||
|
||||
// Sendspin message handling (text and binary)
|
||||
final _sendspinTextController = StreamController<String>.broadcast();
|
||||
final _sendspinBinaryController = StreamController<Uint8List>.broadcast();
|
||||
|
||||
// Server info
|
||||
Map<String, dynamic>? serverInfo;
|
||||
|
||||
// Callbacks
|
||||
Function(WebRTCConnectionState state)? onStateChanged;
|
||||
Function(String error)? onError;
|
||||
|
||||
WebRTCConnectionState get state => _state;
|
||||
Stream<Map<String, dynamic>> get messages => _messageController.stream;
|
||||
Stream<String> get rawMessages => _rawMessageController.stream;
|
||||
bool get isConnected => _state == WebRTCConnectionState.connected;
|
||||
|
||||
// Sendspin channel streams
|
||||
Stream<String> get sendspinTextMessages => _sendspinTextController.stream;
|
||||
Stream<Uint8List> get sendspinBinaryMessages => _sendspinBinaryController.stream;
|
||||
bool get isSendspinConnected =>
|
||||
_sendspinDataChannel?.state == RTCDataChannelState.RTCDataChannelOpen;
|
||||
|
||||
/// Connect to a remote MA server using the Remote Access ID
|
||||
Future<bool> connect(String remoteId) async {
|
||||
if (_state == WebRTCConnectionState.connecting) {
|
||||
DebugLogger().log('WebRTC: Already connecting');
|
||||
return false;
|
||||
}
|
||||
|
||||
_setState(WebRTCConnectionState.connecting);
|
||||
_connectionCompleter = Completer<bool>();
|
||||
|
||||
try {
|
||||
// Set up signaling callbacks
|
||||
_signalingClient.onConnected = _onSignalingConnected;
|
||||
_signalingClient.onAnswer = _onAnswer;
|
||||
_signalingClient.onIceCandidate = _onRemoteIceCandidate;
|
||||
_signalingClient.onError = _onSignalingError;
|
||||
_signalingClient.onPeerDisconnected = _onPeerDisconnected;
|
||||
_signalingClient.onDisconnected = _onSignalingDisconnected;
|
||||
|
||||
// Connect to signaling server
|
||||
final connected = await _signalingClient.connect(remoteId);
|
||||
if (!connected) {
|
||||
_setState(WebRTCConnectionState.failed);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Wait for connection to complete (with timeout)
|
||||
final result = await _connectionCompleter!.future.timeout(
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () {
|
||||
DebugLogger().log('WebRTC: Connection timeout');
|
||||
_onSignalingError('Connection timeout');
|
||||
return false;
|
||||
},
|
||||
);
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
DebugLogger().log('WebRTC: Connection error: $e');
|
||||
_setState(WebRTCConnectionState.failed);
|
||||
onError?.call(e.toString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a JSON-RPC request and wait for response
|
||||
Future<Map<String, dynamic>> sendRequest(
|
||||
String command, [
|
||||
Map<String, dynamic>? params,
|
||||
]) async {
|
||||
if (_dataChannel == null || _dataChannel!.state != RTCDataChannelState.RTCDataChannelOpen) {
|
||||
throw Exception('Data channel not open');
|
||||
}
|
||||
|
||||
final messageId = _uuid.v4();
|
||||
final request = {
|
||||
'message_id': messageId,
|
||||
'command': command,
|
||||
if (params != null) 'args': params,
|
||||
};
|
||||
|
||||
final completer = Completer<Map<String, dynamic>>();
|
||||
_pendingRequests[messageId] = completer;
|
||||
|
||||
final jsonStr = jsonEncode(request);
|
||||
DebugLogger().log('WebRTC: Sending request: $jsonStr');
|
||||
_dataChannel!.send(RTCDataChannelMessage(jsonStr));
|
||||
|
||||
// Timeout after 30 seconds
|
||||
return completer.future.timeout(
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () {
|
||||
_pendingRequests.remove(messageId);
|
||||
throw TimeoutException('Request timed out: $command');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Send a raw message without waiting for response (for bridge passthrough)
|
||||
void sendRaw(String message) {
|
||||
if (_dataChannel == null) {
|
||||
DebugLogger().log('WebRTC: Cannot send raw - data channel is null');
|
||||
return;
|
||||
}
|
||||
|
||||
final state = _dataChannel!.state;
|
||||
if (state != RTCDataChannelState.RTCDataChannelOpen) {
|
||||
DebugLogger().log('WebRTC: Cannot send raw - data channel state: $state');
|
||||
return;
|
||||
}
|
||||
|
||||
DebugLogger().log('WebRTC: Sending raw: ${message.substring(0, message.length > 100 ? 100 : message.length)}...');
|
||||
_dataChannel!.send(RTCDataChannelMessage(message));
|
||||
}
|
||||
|
||||
/// Check if the data channel is healthy
|
||||
bool get isDataChannelHealthy {
|
||||
if (_dataChannel == null) return false;
|
||||
return _dataChannel!.state == RTCDataChannelState.RTCDataChannelOpen;
|
||||
}
|
||||
|
||||
/// Get data channel state for debugging
|
||||
String get dataChannelStateDebug {
|
||||
if (_dataChannel == null) return 'null';
|
||||
return _dataChannel!.state.toString();
|
||||
}
|
||||
|
||||
/// Disconnect from the remote server
|
||||
Future<void> disconnect() async {
|
||||
DebugLogger().log('WebRTC: Disconnecting');
|
||||
|
||||
_signalingClient.disconnect();
|
||||
await _dataChannel?.close();
|
||||
await _sendspinDataChannel?.close();
|
||||
await _peerConnection?.close();
|
||||
|
||||
_dataChannel = null;
|
||||
_sendspinDataChannel = null;
|
||||
_peerConnection = null;
|
||||
|
||||
// Complete all pending requests with an error before clearing
|
||||
_completePendingRequestsWithError('WebRTC connection disconnected');
|
||||
|
||||
_serverHelloReceived = false;
|
||||
_serverHelloCompleter = null;
|
||||
serverInfo = null;
|
||||
|
||||
_setState(WebRTCConnectionState.disconnected);
|
||||
}
|
||||
|
||||
/// Complete all pending requests with an error message
|
||||
void _completePendingRequestsWithError(String reason) {
|
||||
for (final entry in _pendingRequests.entries) {
|
||||
if (!entry.value.isCompleted) {
|
||||
entry.value.completeError(Exception(reason));
|
||||
}
|
||||
}
|
||||
_pendingRequests.clear();
|
||||
}
|
||||
|
||||
void _setState(WebRTCConnectionState newState) {
|
||||
if (_state != newState) {
|
||||
DebugLogger().log('WebRTC: State changed: $_state -> $newState');
|
||||
_state = newState;
|
||||
onStateChanged?.call(newState);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onSignalingConnected(String sessionId, List<IceServer> iceServers) async {
|
||||
DebugLogger().log('WebRTC: Signaling connected, creating peer connection');
|
||||
|
||||
try {
|
||||
// Configure Android audio to NOT manage focus since we only use data channels
|
||||
// This prevents flutter_webrtc from interfering with system audio/speakers
|
||||
await AndroidNativeAudioManagement.setAndroidAudioConfiguration(
|
||||
AndroidAudioConfiguration(
|
||||
manageAudioFocus: false,
|
||||
),
|
||||
);
|
||||
DebugLogger().log('WebRTC: Android audio configured - manageAudioFocus: false');
|
||||
|
||||
// Create peer connection with ICE servers
|
||||
final config = <String, dynamic>{
|
||||
'iceServers': iceServers.map((s) => s.toWebRtcConfig()).toList(),
|
||||
'sdpSemantics': 'unified-plan',
|
||||
};
|
||||
|
||||
DebugLogger().log('WebRTC: ICE servers: ${config['iceServers']}');
|
||||
|
||||
_peerConnection = await createPeerConnection(config);
|
||||
|
||||
// Set up peer connection callbacks
|
||||
_peerConnection!.onIceCandidate = _onLocalIceCandidate;
|
||||
_peerConnection!.onIceConnectionState = _onIceConnectionState;
|
||||
_peerConnection!.onConnectionState = _onConnectionState;
|
||||
_peerConnection!.onDataChannel = _onDataChannel;
|
||||
|
||||
// Create data channel for MA API
|
||||
final dataChannelInit = RTCDataChannelInit()
|
||||
..ordered = true
|
||||
..protocol = 'ma-api';
|
||||
|
||||
_dataChannel = await _peerConnection!.createDataChannel('ma-api', dataChannelInit);
|
||||
_setupDataChannel(_dataChannel!);
|
||||
|
||||
// TEST: Sendspin channel DISABLED to test if multi-channel bug causes disconnects
|
||||
// If stability improves, the flutter_webrtc multi-channel bug is confirmed
|
||||
DebugLogger().log('WebRTC: ⚠️ TEST BUILD - Sendspin channel DISABLED (single channel mode)');
|
||||
// final sendspinChannelInit = RTCDataChannelInit()
|
||||
// ..ordered = true
|
||||
// ..protocol = 'sendspin';
|
||||
// _sendspinDataChannel = await _peerConnection!.createDataChannel('sendspin', sendspinChannelInit);
|
||||
// _setupSendspinDataChannel(_sendspinDataChannel!);
|
||||
|
||||
// Create and send offer
|
||||
final offer = await _peerConnection!.createOffer();
|
||||
await _peerConnection!.setLocalDescription(offer);
|
||||
|
||||
DebugLogger().log('WebRTC: Sending offer');
|
||||
_signalingClient.sendOffer({
|
||||
'type': offer.type,
|
||||
'sdp': offer.sdp,
|
||||
});
|
||||
} catch (e) {
|
||||
DebugLogger().log('WebRTC: Failed to create peer connection: $e');
|
||||
_onSignalingError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onAnswer(Map<String, dynamic> answer) async {
|
||||
DebugLogger().log('WebRTC: Received answer');
|
||||
|
||||
try {
|
||||
final description = RTCSessionDescription(
|
||||
answer['sdp'] as String?,
|
||||
answer['type'] as String?,
|
||||
);
|
||||
await _peerConnection?.setRemoteDescription(description);
|
||||
} catch (e) {
|
||||
DebugLogger().log('WebRTC: Failed to set remote description: $e');
|
||||
_onSignalingError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _onLocalIceCandidate(RTCIceCandidate candidate) {
|
||||
DebugLogger().log('WebRTC: Local ICE candidate: ${candidate.candidate?.substring(0, 50)}...');
|
||||
|
||||
_signalingClient.sendIceCandidate({
|
||||
'candidate': candidate.candidate,
|
||||
'sdpMid': candidate.sdpMid,
|
||||
'sdpMLineIndex': candidate.sdpMLineIndex,
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _onRemoteIceCandidate(Map<String, dynamic> candidateData) async {
|
||||
DebugLogger().log('WebRTC: Remote ICE candidate received');
|
||||
|
||||
try {
|
||||
final candidate = RTCIceCandidate(
|
||||
candidateData['candidate'] as String?,
|
||||
candidateData['sdpMid'] as String?,
|
||||
candidateData['sdpMLineIndex'] as int?,
|
||||
);
|
||||
await _peerConnection?.addCandidate(candidate);
|
||||
} catch (e) {
|
||||
DebugLogger().log('WebRTC: Failed to add ICE candidate: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _onIceConnectionState(RTCIceConnectionState state) {
|
||||
DebugLogger().log('WebRTC: ICE connection state: $state');
|
||||
|
||||
switch (state) {
|
||||
case RTCIceConnectionState.RTCIceConnectionStateFailed:
|
||||
_onSignalingError('ICE connection failed');
|
||||
break;
|
||||
case RTCIceConnectionState.RTCIceConnectionStateDisconnected:
|
||||
DebugLogger().log('WebRTC: ICE disconnected, may recover');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _onConnectionState(RTCPeerConnectionState state) {
|
||||
DebugLogger().log('WebRTC: Peer connection state: $state');
|
||||
|
||||
switch (state) {
|
||||
case RTCPeerConnectionState.RTCPeerConnectionStateConnected:
|
||||
// Connection established, but wait for data channel
|
||||
break;
|
||||
case RTCPeerConnectionState.RTCPeerConnectionStateFailed:
|
||||
_onSignalingError('Peer connection failed');
|
||||
break;
|
||||
case RTCPeerConnectionState.RTCPeerConnectionStateClosed:
|
||||
_setState(WebRTCConnectionState.disconnected);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _onDataChannel(RTCDataChannel channel) {
|
||||
DebugLogger().log('WebRTC: Remote data channel received: ${channel.label}');
|
||||
if (channel.label == 'ma-api') {
|
||||
_dataChannel = channel;
|
||||
_setupDataChannel(channel);
|
||||
} else if (channel.label == 'sendspin') {
|
||||
_sendspinDataChannel = channel;
|
||||
_setupSendspinDataChannel(channel);
|
||||
}
|
||||
}
|
||||
|
||||
void _setupDataChannel(RTCDataChannel channel) {
|
||||
channel.onDataChannelState = (state) {
|
||||
DebugLogger().log('WebRTC: Data channel state: $state');
|
||||
|
||||
if (state == RTCDataChannelState.RTCDataChannelOpen) {
|
||||
DebugLogger().log('WebRTC: Data channel open - waiting for server hello...');
|
||||
// Don't complete yet - wait for server hello
|
||||
_serverHelloCompleter = Completer<void>();
|
||||
_serverHelloCompleter!.future.then((_) {
|
||||
DebugLogger().log('WebRTC: Server hello received - connection complete!');
|
||||
_setState(WebRTCConnectionState.connected);
|
||||
_safeCompleteConnection(true);
|
||||
});
|
||||
} else if (state == RTCDataChannelState.RTCDataChannelClosed) {
|
||||
DebugLogger().log('WebRTC: Data channel closed, completing pending requests with error');
|
||||
_completePendingRequestsWithError('Data channel closed');
|
||||
_setState(WebRTCConnectionState.disconnected);
|
||||
}
|
||||
};
|
||||
|
||||
channel.onMessage = _onDataChannelMessage;
|
||||
}
|
||||
|
||||
void _onDataChannelMessage(RTCDataChannelMessage message) {
|
||||
try {
|
||||
DebugLogger().log('WebRTC: Raw message: ${message.text.substring(0, message.text.length > 200 ? 200 : message.text.length)}...');
|
||||
final data = jsonDecode(message.text) as Map<String, dynamic>;
|
||||
final messageId = data['message_id']?.toString();
|
||||
|
||||
DebugLogger().log('WebRTC: Parsed message keys: ${data.keys.toList()}, message_id: $messageId');
|
||||
|
||||
// Check for server hello message (has server_id but no message_id)
|
||||
if (data.containsKey('server_id') && messageId == null && !_serverHelloReceived) {
|
||||
DebugLogger().log('WebRTC: Server hello received - server_version: ${data['server_version']}');
|
||||
serverInfo = data;
|
||||
_serverHelloReceived = true;
|
||||
_serverHelloCompleter?.complete();
|
||||
// Don't forward server hello to rawMessages - bridge caches it separately
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is a response to a pending request (for internal use like auth)
|
||||
if (messageId != null && _pendingRequests.containsKey(messageId)) {
|
||||
DebugLogger().log('WebRTC: Matched pending request $messageId');
|
||||
_pendingRequests.remove(messageId)?.complete(data);
|
||||
// Don't forward to rawMessages - this was an internal request
|
||||
return;
|
||||
}
|
||||
|
||||
// Forward all other messages to rawMessages stream (for bridge passthrough)
|
||||
_rawMessageController.add(message.text);
|
||||
|
||||
// Also broadcast parsed event/notification for internal listeners
|
||||
DebugLogger().log('WebRTC: No match for message_id=$messageId, pending: ${_pendingRequests.keys.toList()}');
|
||||
_messageController.add(data);
|
||||
} catch (e) {
|
||||
DebugLogger().log('WebRTC: Failed to parse message: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Setup Sendspin data channel for audio streaming
|
||||
void _setupSendspinDataChannel(RTCDataChannel channel) {
|
||||
channel.onDataChannelState = (state) {
|
||||
DebugLogger().log('WebRTC: Sendspin data channel state: $state');
|
||||
};
|
||||
|
||||
channel.onMessage = _onSendspinMessage;
|
||||
}
|
||||
|
||||
/// Handle incoming Sendspin messages (both text and binary)
|
||||
void _onSendspinMessage(RTCDataChannelMessage message) {
|
||||
if (message.isBinary) {
|
||||
// Binary audio data
|
||||
final bytes = message.binary;
|
||||
if (bytes != null && !_sendspinBinaryController.isClosed) {
|
||||
_sendspinBinaryController.add(bytes);
|
||||
}
|
||||
} else {
|
||||
// Text control message (JSON)
|
||||
final text = message.text;
|
||||
DebugLogger().log('WebRTC: Sendspin text message: ${text.substring(0, text.length > 100 ? 100 : text.length)}...');
|
||||
if (!_sendspinTextController.isClosed) {
|
||||
_sendspinTextController.add(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a text message to Sendspin channel (JSON control messages)
|
||||
void sendSendspinText(String message) {
|
||||
if (_sendspinDataChannel == null) {
|
||||
DebugLogger().log('WebRTC: Cannot send sendspin text - channel is null');
|
||||
return;
|
||||
}
|
||||
|
||||
final state = _sendspinDataChannel!.state;
|
||||
if (state != RTCDataChannelState.RTCDataChannelOpen) {
|
||||
DebugLogger().log('WebRTC: Cannot send sendspin text - channel state: $state');
|
||||
return;
|
||||
}
|
||||
|
||||
_sendspinDataChannel!.send(RTCDataChannelMessage(message));
|
||||
}
|
||||
|
||||
/// Send binary data to Sendspin channel (audio data from local player)
|
||||
void sendSendspinBinary(Uint8List data) {
|
||||
if (_sendspinDataChannel == null) {
|
||||
DebugLogger().log('WebRTC: Cannot send sendspin binary - channel is null');
|
||||
return;
|
||||
}
|
||||
|
||||
final state = _sendspinDataChannel!.state;
|
||||
if (state != RTCDataChannelState.RTCDataChannelOpen) {
|
||||
DebugLogger().log('WebRTC: Cannot send sendspin binary - channel state: $state');
|
||||
return;
|
||||
}
|
||||
|
||||
_sendspinDataChannel!.send(RTCDataChannelMessage.fromBinary(data));
|
||||
}
|
||||
|
||||
void _onSignalingError(String error) {
|
||||
DebugLogger().log('WebRTC: Signaling error: $error');
|
||||
_setState(WebRTCConnectionState.failed);
|
||||
onError?.call(error);
|
||||
_safeCompleteConnection(false);
|
||||
}
|
||||
|
||||
void _onPeerDisconnected() {
|
||||
DebugLogger().log('WebRTC: Peer disconnected, completing pending requests with error');
|
||||
_completePendingRequestsWithError('Remote peer disconnected');
|
||||
_setState(WebRTCConnectionState.disconnected);
|
||||
onError?.call('Remote server disconnected');
|
||||
}
|
||||
|
||||
void _onSignalingDisconnected() {
|
||||
DebugLogger().log('WebRTC: Signaling disconnected');
|
||||
// Only set failed if we were still connecting
|
||||
if (_state == WebRTCConnectionState.connecting) {
|
||||
_setState(WebRTCConnectionState.failed);
|
||||
_safeCompleteConnection(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Safely complete the connection completer (only once)
|
||||
void _safeCompleteConnection(bool success) {
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
_connectionCompleter!.complete(success);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_messageController.close();
|
||||
_rawMessageController.close();
|
||||
_sendspinTextController.close();
|
||||
_sendspinBinaryController.close();
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,6 @@ class SendspinService {
|
||||
WebSocketChannel? _channel;
|
||||
Timer? _heartbeatTimer;
|
||||
Timer? _reconnectTimer;
|
||||
int _reconnectAttempts = 0;
|
||||
static const int _maxReconnectAttempts = 10;
|
||||
static const Duration _baseReconnectDelay = Duration(seconds: 3);
|
||||
static const Duration _maxReconnectDelay = Duration(seconds: 60);
|
||||
|
||||
// Connection state
|
||||
SendspinConnectionState _state = SendspinConnectionState.disconnected;
|
||||
@@ -283,7 +279,6 @@ class SendspinService {
|
||||
|
||||
_logger.log('Sendspin: Connected and registered successfully');
|
||||
_updateState(SendspinConnectionState.connected);
|
||||
_resetReconnectAttempts();
|
||||
_startHeartbeat();
|
||||
|
||||
return true;
|
||||
@@ -564,7 +559,6 @@ class SendspinService {
|
||||
'state': playerState,
|
||||
'volume': _volume,
|
||||
'muted': _isMuted,
|
||||
'position': _position,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -633,7 +627,6 @@ class SendspinService {
|
||||
'state': 'synchronized',
|
||||
'volume': _volume,
|
||||
'muted': _isMuted,
|
||||
'position': _position,
|
||||
},
|
||||
},
|
||||
}, allowDuringHandshake: true);
|
||||
@@ -645,27 +638,12 @@ class SendspinService {
|
||||
_heartbeatTimer = null;
|
||||
}
|
||||
|
||||
/// Schedule reconnection attempt with exponential backoff
|
||||
/// Schedule reconnection attempt
|
||||
void _scheduleReconnect() {
|
||||
if (_isDisposed) return;
|
||||
|
||||
if (_reconnectAttempts >= _maxReconnectAttempts) {
|
||||
_logger.log('Sendspin: Max reconnection attempts reached ($_maxReconnectAttempts), giving up');
|
||||
_updateState(SendspinConnectionState.disconnected);
|
||||
return;
|
||||
}
|
||||
|
||||
_reconnectAttempts++;
|
||||
|
||||
// Calculate exponential backoff delay: 3s, 6s, 12s, 24s, 48s, then cap at 60s
|
||||
final delaySeconds = (_baseReconnectDelay.inSeconds * (1 << (_reconnectAttempts - 1)))
|
||||
.clamp(0, _maxReconnectDelay.inSeconds);
|
||||
final delay = Duration(seconds: delaySeconds);
|
||||
|
||||
_logger.log('Sendspin: Scheduling reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts in ${delay.inSeconds}s');
|
||||
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = Timer(delay, () {
|
||||
_reconnectTimer = Timer(const Duration(seconds: 5), () {
|
||||
if (!_isDisposed && _state != SendspinConnectionState.connected) {
|
||||
_logger.log('Sendspin: Attempting reconnection...');
|
||||
if (_connectedUrl != null) {
|
||||
@@ -675,19 +653,11 @@ class SendspinService {
|
||||
});
|
||||
}
|
||||
|
||||
/// Reset reconnection attempts counter (call on successful connection)
|
||||
void _resetReconnectAttempts() {
|
||||
_reconnectAttempts = 0;
|
||||
}
|
||||
|
||||
/// Update connection state
|
||||
void _updateState(SendspinConnectionState newState) {
|
||||
if (_state != newState) {
|
||||
_state = newState;
|
||||
// Don't add events if controller is closed (disposed)
|
||||
if (!_isDisposed) {
|
||||
_stateController.add(newState);
|
||||
}
|
||||
_stateController.add(newState);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,6 @@ class SettingsService {
|
||||
static const String _keyServerUrl = 'server_url';
|
||||
static const String _keyAuthServerUrl = 'auth_server_url';
|
||||
static const String _keyWebSocketPort = 'websocket_port';
|
||||
static const String _keyRemoteAccessId = 'remote_access_id'; // MA Remote Access ID for WebRTC
|
||||
static const String _keyAuthToken = 'auth_token';
|
||||
static const String _keyMaAuthToken = 'ma_auth_token'; // Music Assistant native auth token
|
||||
static const String _keyAuthCredentials = 'auth_credentials'; // NEW: Serialized auth strategy credentials
|
||||
@@ -179,6 +178,9 @@ class SettingsService {
|
||||
// Podcast Cover Cache (iTunes URLs for high-res artwork)
|
||||
static const String _keyPodcastCoverCache = 'podcast_cover_cache';
|
||||
|
||||
// Remote Access Settings
|
||||
static const String _keyRemoteAccessId = 'remote_access_id';
|
||||
|
||||
static Future<String?> getServerUrl() async {
|
||||
final prefs = await _getPrefs();
|
||||
return prefs.getString(_keyServerUrl);
|
||||
@@ -194,26 +196,6 @@ class SettingsService {
|
||||
await prefs.remove(_keyServerUrl);
|
||||
}
|
||||
|
||||
// Remote Access ID for WebRTC-based remote connections
|
||||
static Future<String?> getRemoteAccessId() async {
|
||||
final prefs = await _getPrefs();
|
||||
return prefs.getString(_keyRemoteAccessId);
|
||||
}
|
||||
|
||||
static Future<void> setRemoteAccessId(String? id) async {
|
||||
final prefs = await _getPrefs();
|
||||
if (id == null || id.isEmpty) {
|
||||
await prefs.remove(_keyRemoteAccessId);
|
||||
} else {
|
||||
await prefs.setString(_keyRemoteAccessId, id);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> clearRemoteAccessId() async {
|
||||
final prefs = await _getPrefs();
|
||||
await prefs.remove(_keyRemoteAccessId);
|
||||
}
|
||||
|
||||
// Get authentication server URL (returns null if not set, meaning use server URL)
|
||||
static Future<String?> getAuthServerUrl() async {
|
||||
final prefs = await _getPrefs();
|
||||
@@ -286,6 +268,22 @@ class SettingsService {
|
||||
await SecureStorageService.clearAuthCredentials();
|
||||
}
|
||||
|
||||
// Get Remote Access ID for remote connections
|
||||
static Future<String?> getRemoteAccessId() async {
|
||||
final prefs = await _getPrefs();
|
||||
return prefs.getString(_keyRemoteAccessId);
|
||||
}
|
||||
|
||||
// Set Remote Access ID for remote connections
|
||||
static Future<void> setRemoteAccessId(String? id) async {
|
||||
final prefs = await _getPrefs();
|
||||
if (id == null || id.isEmpty) {
|
||||
await prefs.remove(_keyRemoteAccessId);
|
||||
} else {
|
||||
await prefs.setString(_keyRemoteAccessId, id);
|
||||
}
|
||||
}
|
||||
|
||||
// Get username for authentication
|
||||
static Future<String?> getUsername() async {
|
||||
final prefs = await _getPrefs();
|
||||
|
||||
@@ -242,44 +242,24 @@ class SyncService with ChangeNotifier {
|
||||
final playlistMap = <String, Playlist>{};
|
||||
|
||||
// If specific providers are requested, sync each separately for accurate source tracking
|
||||
// Use smaller batches in remote mode to avoid WebRTC message size issues
|
||||
final limit = api.isRemoteMode ? 100 : 1000;
|
||||
|
||||
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty) {
|
||||
_logger.log('🔒 Per-provider sync for ${providerInstanceIds.length} providers (limit: $limit, remote: ${api.isRemoteMode})');
|
||||
_logger.log('🔒 Per-provider sync for ${providerInstanceIds.length} providers');
|
||||
|
||||
for (final providerId in providerInstanceIds) {
|
||||
_logger.log(' 📡 Syncing provider: $providerId');
|
||||
|
||||
List<Album> albums;
|
||||
List<Artist> artists;
|
||||
List<Audiobook> audiobooks;
|
||||
List<Playlist> playlists;
|
||||
// Fetch from this specific provider
|
||||
final results = await Future.wait([
|
||||
api.getAlbums(limit: 1000, providerInstanceIds: [providerId]),
|
||||
api.getArtists(limit: 1000, albumArtistsOnly: showOnlyArtistsWithAlbums, providerInstanceIds: [providerId]),
|
||||
api.getAudiobooks(limit: 1000, providerInstanceIds: [providerId]),
|
||||
api.getPlaylists(limit: 1000, providerInstanceIds: [providerId]),
|
||||
]);
|
||||
|
||||
// In remote mode, do sequential requests to avoid overwhelming WebRTC
|
||||
if (api.isRemoteMode) {
|
||||
albums = await api.getAlbums(limit: limit, providerInstanceIds: [providerId]);
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
artists = await api.getArtists(limit: limit, albumArtistsOnly: showOnlyArtistsWithAlbums, providerInstanceIds: [providerId]);
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
audiobooks = await api.getAudiobooks(limit: limit, providerInstanceIds: [providerId]);
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
playlists = await api.getPlaylists(limit: limit, providerInstanceIds: [providerId]);
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
} else {
|
||||
// Local mode: parallel requests for speed
|
||||
final results = await Future.wait([
|
||||
api.getAlbums(limit: limit, providerInstanceIds: [providerId]),
|
||||
api.getArtists(limit: limit, albumArtistsOnly: showOnlyArtistsWithAlbums, providerInstanceIds: [providerId]),
|
||||
api.getAudiobooks(limit: limit, providerInstanceIds: [providerId]),
|
||||
api.getPlaylists(limit: limit, providerInstanceIds: [providerId]),
|
||||
]);
|
||||
|
||||
albums = results[0] as List<Album>;
|
||||
artists = results[1] as List<Artist>;
|
||||
audiobooks = results[2] as List<Audiobook>;
|
||||
playlists = results[3] as List<Playlist>;
|
||||
}
|
||||
final albums = results[0] as List<Album>;
|
||||
final artists = results[1] as List<Artist>;
|
||||
final audiobooks = results[2] as List<Audiobook>;
|
||||
final playlists = results[3] as List<Playlist>;
|
||||
|
||||
_logger.log(' 📥 Got ${albums.length} albums, ${artists.length} artists, ${audiobooks.length} audiobooks from $providerId');
|
||||
|
||||
@@ -315,59 +295,26 @@ class SyncService with ChangeNotifier {
|
||||
}
|
||||
} else {
|
||||
// No provider filter - fetch all at once (faster, but no source tracking)
|
||||
_logger.log('📡 Fetching from all providers (no source tracking, limit: $limit)');
|
||||
_logger.log('📡 Fetching from all providers (no source tracking)');
|
||||
|
||||
// In remote mode, do sequential requests to avoid overwhelming WebRTC
|
||||
if (api.isRemoteMode) {
|
||||
_logger.log('🌐 Remote mode: using sequential requests with delays');
|
||||
final results = await Future.wait([
|
||||
api.getAlbums(limit: 1000),
|
||||
api.getArtists(limit: 1000, albumArtistsOnly: showOnlyArtistsWithAlbums),
|
||||
api.getAudiobooks(limit: 1000),
|
||||
api.getPlaylists(limit: 1000),
|
||||
]);
|
||||
|
||||
final albums = await api.getAlbums(limit: limit);
|
||||
for (final album in albums) {
|
||||
albumMap[album.itemId] = album;
|
||||
}
|
||||
_logger.log(' 📥 Got ${albums.length} albums');
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
final artists = await api.getArtists(limit: limit, albumArtistsOnly: showOnlyArtistsWithAlbums);
|
||||
for (final artist in artists) {
|
||||
artistMap[artist.itemId] = artist;
|
||||
}
|
||||
_logger.log(' 📥 Got ${artists.length} artists');
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
final audiobooks = await api.getAudiobooks(limit: limit);
|
||||
for (final audiobook in audiobooks) {
|
||||
audiobookMap[audiobook.itemId] = audiobook;
|
||||
}
|
||||
_logger.log(' 📥 Got ${audiobooks.length} audiobooks');
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
final playlists = await api.getPlaylists(limit: limit);
|
||||
for (final playlist in playlists) {
|
||||
playlistMap[playlist.itemId] = playlist;
|
||||
}
|
||||
_logger.log(' 📥 Got ${playlists.length} playlists');
|
||||
} else {
|
||||
// Local mode: parallel requests for speed
|
||||
final results = await Future.wait([
|
||||
api.getAlbums(limit: limit),
|
||||
api.getArtists(limit: limit, albumArtistsOnly: showOnlyArtistsWithAlbums),
|
||||
api.getAudiobooks(limit: limit),
|
||||
api.getPlaylists(limit: limit),
|
||||
]);
|
||||
|
||||
for (final album in results[0] as List<Album>) {
|
||||
albumMap[album.itemId] = album;
|
||||
}
|
||||
for (final artist in results[1] as List<Artist>) {
|
||||
artistMap[artist.itemId] = artist;
|
||||
}
|
||||
for (final audiobook in results[2] as List<Audiobook>) {
|
||||
audiobookMap[audiobook.itemId] = audiobook;
|
||||
}
|
||||
for (final playlist in results[3] as List<Playlist>) {
|
||||
playlistMap[playlist.itemId] = playlist;
|
||||
}
|
||||
for (final album in results[0] as List<Album>) {
|
||||
albumMap[album.itemId] = album;
|
||||
}
|
||||
for (final artist in results[1] as List<Artist>) {
|
||||
artistMap[artist.itemId] = artist;
|
||||
}
|
||||
for (final audiobook in results[2] as List<Audiobook>) {
|
||||
audiobookMap[audiobook.itemId] = audiobook;
|
||||
}
|
||||
for (final playlist in results[3] as List<Playlist>) {
|
||||
playlistMap[playlist.itemId] = playlist;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -121,7 +121,6 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
StreamSubscription<Map<String, dynamic>>? _queueItemsSubscription;
|
||||
final ValueNotifier<int> _progressNotifier = ValueNotifier<int>(0);
|
||||
final ValueNotifier<double?> _seekPositionNotifier = ValueNotifier<double?>(null);
|
||||
bool _isSeeking = false; // Debounce flag to prevent rapid-fire seeks
|
||||
|
||||
// Pre-computed static colors to avoid object creation during animation frames
|
||||
static const Color _shadowColor = Color(0x4D000000); // Colors.black.withOpacity(0.3)
|
||||
@@ -2861,14 +2860,33 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 48, // Increase touch target height
|
||||
child: _buildProgressSlider(
|
||||
context,
|
||||
currentProgress,
|
||||
currentTrack.duration!.inSeconds.toDouble(),
|
||||
primaryColor,
|
||||
primaryColor20,
|
||||
maProvider,
|
||||
selectedPlayer.playerId,
|
||||
// PERF Phase 1: Use cached SliderThemeData
|
||||
child: SliderTheme(
|
||||
data: _sliderTheme,
|
||||
child: Slider(
|
||||
value: currentProgress.clamp(0.0, currentTrack.duration!.inSeconds.toDouble()).toDouble(),
|
||||
max: currentTrack.duration!.inSeconds.toDouble(),
|
||||
onChanged: (value) => _seekPositionNotifier.value = value,
|
||||
onChangeStart: (value) => _seekPositionNotifier.value = value,
|
||||
onChangeEnd: (value) async {
|
||||
try {
|
||||
await maProvider.seek(selectedPlayer.playerId, value.round());
|
||||
await Future.delayed(const Duration(milliseconds: 200));
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.errorSeeking(e.toString()))),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
_seekPositionNotifier.value = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
activeColor: primaryColor,
|
||||
inactiveColor: primaryColor20, // PERF: Use cached color
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
@@ -4114,140 +4132,6 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Custom progress slider that doesn't require Overlay widget
|
||||
/// (Flutter 3.38's Material 3 Slider uses OverlayPortal which fails in our overlay context)
|
||||
Widget _buildProgressSlider(
|
||||
BuildContext context,
|
||||
double currentProgress,
|
||||
double maxProgress,
|
||||
Color activeColor,
|
||||
Color inactiveColor,
|
||||
MusicAssistantProvider maProvider,
|
||||
String playerId,
|
||||
) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final progress = maxProgress > 0 ? (currentProgress / maxProgress).clamp(0.0, 1.0) : 0.0;
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onHorizontalDragStart: (details) {
|
||||
final newProgress = (details.localPosition.dx / width).clamp(0.0, 1.0);
|
||||
_seekPositionNotifier.value = newProgress * maxProgress;
|
||||
},
|
||||
onHorizontalDragUpdate: (details) {
|
||||
final newProgress = (details.localPosition.dx / width).clamp(0.0, 1.0);
|
||||
_seekPositionNotifier.value = newProgress * maxProgress;
|
||||
},
|
||||
onHorizontalDragCancel: () {
|
||||
_seekPositionNotifier.value = null;
|
||||
},
|
||||
onHorizontalDragEnd: (details) async {
|
||||
final seekPosition = _seekPositionNotifier.value;
|
||||
if (seekPosition != null && !_isSeeking) {
|
||||
_isSeeking = true;
|
||||
try {
|
||||
await maProvider.seek(playerId, seekPosition.round());
|
||||
// Wait for server to process seek before allowing another
|
||||
await Future.delayed(const Duration(milliseconds: 1500));
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.errorSeeking(e.toString()))),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
_isSeeking = false;
|
||||
if (mounted) {
|
||||
_seekPositionNotifier.value = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onTapUp: (details) async {
|
||||
if (_isSeeking) return; // Ignore if already seeking
|
||||
|
||||
// Calculate position from tap location
|
||||
final newProgress = (details.localPosition.dx / width).clamp(0.0, 1.0);
|
||||
final seekPosition = newProgress * maxProgress;
|
||||
_seekPositionNotifier.value = seekPosition;
|
||||
_isSeeking = true;
|
||||
|
||||
try {
|
||||
await maProvider.seek(playerId, seekPosition.round());
|
||||
// Wait for server to process seek before allowing another
|
||||
await Future.delayed(const Duration(milliseconds: 1500));
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.errorSeeking(e.toString()))),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
_isSeeking = false;
|
||||
if (mounted) {
|
||||
_seekPositionNotifier.value = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
height: 20,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// Inactive track (full width, thinner)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 8.5,
|
||||
child: Container(
|
||||
height: 3,
|
||||
decoration: BoxDecoration(
|
||||
color: inactiveColor,
|
||||
borderRadius: BorderRadius.circular(1.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Active track
|
||||
Positioned(
|
||||
left: 0,
|
||||
top: 7,
|
||||
child: Container(
|
||||
width: width * progress,
|
||||
height: 6,
|
||||
decoration: BoxDecoration(
|
||||
color: activeColor,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Thumb
|
||||
Positioned(
|
||||
left: (width * progress) - 7,
|
||||
top: 3,
|
||||
child: Container(
|
||||
width: 14,
|
||||
height: 14,
|
||||
decoration: BoxDecoration(
|
||||
color: activeColor,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a single line of synced lyrics with timestamp
|
||||
|
||||
@@ -225,8 +225,11 @@ class _VolumeControlState extends State<VolumeControl> {
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final sliderWidth = constraints.maxWidth;
|
||||
// Calculate thumb position for the custom slider track
|
||||
final thumbPosition = sliderWidth * currentVolume.clamp(0.0, 1.0);
|
||||
// Calculate thumb position to match Flutter Slider's internal positioning
|
||||
// The Slider uses overlayRadius as padding on each side for the track
|
||||
const overlayRadius = 20.0; // Must match SliderThemeData overlayShape
|
||||
final thumbPosition = overlayRadius +
|
||||
(currentVolume.clamp(0.0, 1.0) * (sliderWidth - 2 * overlayRadius));
|
||||
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
@@ -308,56 +311,22 @@ class _VolumeControlState extends State<VolumeControl> {
|
||||
_pendingVolume = null;
|
||||
});
|
||||
},
|
||||
// Custom slider track (no Overlay needed - Flutter 3.38 Slider uses OverlayPortal)
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
height: 20,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// Inactive track (full width, thinner)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 8.5,
|
||||
child: Container(
|
||||
height: 3,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(1.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Active track
|
||||
Positioned(
|
||||
left: 0,
|
||||
top: 7,
|
||||
child: Container(
|
||||
width: sliderWidth * currentVolume.clamp(0.0, 1.0),
|
||||
height: 6,
|
||||
decoration: BoxDecoration(
|
||||
color: _inPrecisionMode ? accentColor : Colors.white,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Thumb
|
||||
Positioned(
|
||||
left: (sliderWidth * currentVolume.clamp(0.0, 1.0)) - 6,
|
||||
top: 4,
|
||||
child: Container(
|
||||
width: 12,
|
||||
height: 12,
|
||||
decoration: BoxDecoration(
|
||||
color: _inPrecisionMode ? accentColor : Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: SliderTheme(
|
||||
data: SliderThemeData(
|
||||
trackHeight: 2,
|
||||
thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
|
||||
overlayShape: const RoundSliderOverlayShape(overlayRadius: 20),
|
||||
activeTrackColor: _inPrecisionMode ? accentColor : Colors.white,
|
||||
inactiveTrackColor: Colors.white.withOpacity(0.3),
|
||||
thumbColor: _inPrecisionMode ? accentColor : Colors.white,
|
||||
overlayColor: (_inPrecisionMode ? accentColor : Colors.white).withOpacity(0.2),
|
||||
),
|
||||
child: AbsorbPointer(
|
||||
// AbsorbPointer prevents Slider from handling gestures
|
||||
// Our GestureDetector handles everything for live updates
|
||||
child: Slider(
|
||||
value: currentVolume.clamp(0.0, 1.0),
|
||||
onChanged: (_) {},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
+14
-78
@@ -261,10 +261,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dart_webrtc
|
||||
sha256: "4ed7b9fa9924e5a81eb39271e2c2356739dd1039d60a13b86ba6c5f448625086"
|
||||
sha256: "51bcda4ba5d7dd9e65a309244ce3ac0b58025e6e1f6d7442cee4cd02134ef65f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.7.0"
|
||||
version: "1.6.0"
|
||||
device_info_plus:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -358,70 +358,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.4.1"
|
||||
flutter_inappwebview:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_inappwebview
|
||||
sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.1.5"
|
||||
flutter_inappwebview_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_android
|
||||
sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.3"
|
||||
flutter_inappwebview_internal_annotations:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_internal_annotations
|
||||
sha256: "787171d43f8af67864740b6f04166c13190aa74a1468a1f1f1e9ee5b90c359cd"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
flutter_inappwebview_ios:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_ios
|
||||
sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_macos
|
||||
sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_platform_interface
|
||||
sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.0+1"
|
||||
flutter_inappwebview_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_web
|
||||
sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_windows
|
||||
sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.0"
|
||||
flutter_launcher_icons:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -537,10 +473,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_webrtc
|
||||
sha256: "792aa1e5838a719f29ae52c0773dbb5dd781fc33b1bf87c321b274e55ab51ad1"
|
||||
sha256: "71a38363a5b50603e405c275f30de2eb90f980b0cc94b0e1e9d8b9d6a6b03bf0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.14.2"
|
||||
version: "1.2.1"
|
||||
frontend_server_client:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -685,6 +621,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.0"
|
||||
logger:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: logger
|
||||
sha256: a7967e31b703831a893bbc3c3dd11db08126fe5f369b5c648a36f821979f5be3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.6.2"
|
||||
logging:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -733,14 +677,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
mobile_scanner:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: mobile_scanner
|
||||
sha256: "0b466a0a8a211b366c2e87f3345715faef9b6011c7147556ad22f37de6ba3173"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.0.11"
|
||||
nested:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1286,10 +1222,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webrtc_interface
|
||||
sha256: ad0e5786b2acd3be72a3219ef1dde9e1cac071cf4604c685f11b61d63cdd6eb3
|
||||
sha256: "2e604a31703ad26781782fb14fa8a4ee621154ee2c513d2b9938e486fa695233"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
version: "1.3.0"
|
||||
win32:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
+4
-5
@@ -11,7 +11,7 @@ dependencies:
|
||||
sdk: flutter
|
||||
flutter_localizations:
|
||||
sdk: flutter
|
||||
intl: ^0.20.0
|
||||
intl: ^0.20.2
|
||||
|
||||
# UI
|
||||
material_design_icons_flutter: ^7.0.7296
|
||||
@@ -26,8 +26,9 @@ dependencies:
|
||||
web_socket_channel: ^2.4.0
|
||||
http: ^1.1.0
|
||||
cached_network_image: ^3.3.1
|
||||
flutter_webrtc: ^0.14.1
|
||||
flutter_inappwebview: ^6.0.0
|
||||
|
||||
# WebRTC (for remote access)
|
||||
flutter_webrtc: ^1.2.1
|
||||
|
||||
# Storage
|
||||
shared_preferences: ^2.2.2
|
||||
@@ -42,7 +43,6 @@ dependencies:
|
||||
package_info_plus: ^8.0.0
|
||||
device_info_plus: ^10.1.0
|
||||
share_plus: ^10.1.4
|
||||
mobile_scanner: ^6.0.2
|
||||
|
||||
# Audio - Local Playback
|
||||
just_audio: ^0.9.36
|
||||
@@ -67,7 +67,6 @@ flutter:
|
||||
|
||||
assets:
|
||||
- assets/images/
|
||||
- assets/webrtc_engine.js
|
||||
|
||||
flutter_launcher_icons:
|
||||
android: true
|
||||
|
||||
Reference in New Issue
Block a user