From 5683ab5158e99a9a6b930cebde6836534e502883 Mon Sep 17 00:00:00 2001 From: Yegor Vialov Date: Wed, 13 May 2020 12:46:25 +0000 Subject: [PATCH] WIP: App settings refactoring --- lib/cards/badges.dart | 2 +- .../camera/widgets/camera_stream_view.dart | 4 +- lib/entities/entity_wrapper.class.dart | 6 +- lib/home_assistant.class.dart | 6 +- lib/main.dart | 7 +- lib/managers/app_settings.dart | 68 +++++++++++++++++-- lib/managers/connection_manager.class.dart | 40 +++-------- lib/managers/location_manager.class.dart | 53 ++++++--------- .../mobile_app_integration_manager.class.dart | 22 +++--- lib/pages/main/main.page.dart | 4 +- lib/pages/settings/app_settings.page.dart | 2 +- .../settings/connection_settings.part.dart | 2 +- .../settings/integration_settings.part.dart | 5 +- .../settings/lookandfeel_settings.part.dart | 2 +- lib/panels/config_panel_widget.dart | 2 +- lib/panels/panel_class.dart | 2 +- lib/popups.dart | 6 +- lib/utils/launcher.dart | 2 +- 18 files changed, 129 insertions(+), 106 deletions(-) diff --git a/lib/cards/badges.dart b/lib/cards/badges.dart index b68ab2e..e650240 100644 --- a/lib/cards/badges.dart +++ b/lib/cards/badges.dart @@ -10,7 +10,7 @@ class Badges extends StatelessWidget { List entitiesToShow = badges.getEntitiesToShow(); if (entitiesToShow.isNotEmpty) { - if (ConnectionManager().scrollBadges) { + if (AppSettings().scrollBadges) { return ConstrainedBox( constraints: BoxConstraints.tightFor(height: 112), child: SingleChildScrollView( diff --git a/lib/entities/camera/widgets/camera_stream_view.dart b/lib/entities/camera/widgets/camera_stream_view.dart index 14878c9..bb413bf 100644 --- a/lib/entities/camera/widgets/camera_stream_view.dart +++ b/lib/entities/camera/widgets/camera_stream_view.dart @@ -42,7 +42,7 @@ class _CameraStreamViewState extends State { _jsMessageChannelName = 'HA_${_entity.entityId.replaceAll('.', '_')}'; rootBundle.loadString('assets/html/cameraLiveView.html').then((file) { _webViewHtml = Uri.dataFromString( - file.replaceFirst('{{stream_url}}', '${ConnectionManager().httpWebHost}${data["url"]}').replaceFirst('{{message_channel}}', _jsMessageChannelName), + file.replaceFirst('{{stream_url}}', '${AppSettings().httpWebHost}${data["url"]}').replaceFirst('{{message_channel}}', _jsMessageChannelName), mimeType: 'text/html', encoding: Encoding.getByName('utf-8') ).toString(); @@ -69,7 +69,7 @@ class _CameraStreamViewState extends State { } Future _loadMJPEG() async { - _streamUrl = '${ConnectionManager().httpWebHost}/api/camera_proxy_stream/${_entity + _streamUrl = '${AppSettings().httpWebHost}/api/camera_proxy_stream/${_entity .entityId}?token=${_entity.attributes['access_token']}'; _jsMessageChannelName = 'HA_${_entity.entityId.replaceAll('.', '_')}'; var file = await rootBundle.loadString('assets/html/cameraView.html'); diff --git a/lib/entities/entity_wrapper.class.dart b/lib/entities/entity_wrapper.class.dart index 5233e5f..55f8d40 100644 --- a/lib/entities/entity_wrapper.class.dart +++ b/lib/entities/entity_wrapper.class.dart @@ -61,7 +61,7 @@ class EntityWrapper { case EntityUIAction.navigate: { if (uiAction.tapService != null && uiAction.tapService.startsWith("/")) { //TODO handle local urls - Launcher.launchURLInBrowser('${ConnectionManager().httpWebHost}${uiAction.tapService}'); + Launcher.launchURLInBrowser('${AppSettings().httpWebHost}${uiAction.tapService}'); } else { Launcher.launchURLInBrowser(uiAction.tapService); } @@ -101,7 +101,7 @@ class EntityWrapper { case EntityUIAction.navigate: { if (uiAction.holdService != null && uiAction.holdService.startsWith("/")) { //TODO handle local urls - Launcher.launchURLInBrowser('${ConnectionManager().httpWebHost}${uiAction.holdService}'); + Launcher.launchURLInBrowser('${AppSettings().httpWebHost}${uiAction.holdService}'); } else { Launcher.launchURLInBrowser(uiAction.holdService); } @@ -141,7 +141,7 @@ class EntityWrapper { case EntityUIAction.navigate: { if (uiAction.doubleTapService != null && uiAction.doubleTapService.startsWith("/")) { //TODO handle local urls - Launcher.launchURLInBrowser('${ConnectionManager().httpWebHost}${uiAction.doubleTapService}'); + Launcher.launchURLInBrowser('${AppSettings().httpWebHost}${uiAction.doubleTapService}'); } else { Launcher.launchURLInBrowser(uiAction.doubleTapService); } diff --git a/lib/home_assistant.class.dart b/lib/home_assistant.class.dart index d05671c..6b2dbad 100644 --- a/lib/home_assistant.class.dart +++ b/lib/home_assistant.class.dart @@ -63,7 +63,7 @@ class HomeAssistant { _fetchCompleter = Completer(); List futures = []; if (!uiOnly) { - if (entities == null) entities = EntityCollection(ConnectionManager().httpWebHost); + if (entities == null) entities = EntityCollection(AppSettings().httpWebHost); futures.add(_getStates(null)); futures.add(_getConfig(null)); futures.add(_getUserInfo(null)); @@ -92,7 +92,7 @@ class HomeAssistant { SharedPreferences prefs = await SharedPreferences.getInstance(); bool cached = prefs.getBool('cached'); if (cached != null && cached) { - if (entities == null) entities = EntityCollection(ConnectionManager().httpWebHost); + if (entities == null) entities = EntityCollection(AppSettings().httpWebHost); try { _getStates(prefs); if (!autoUi) { @@ -194,7 +194,7 @@ class HomeAssistant { } else { Completer completer = Completer(); var additionalData; - if (ConnectionManager().haVersion >= 107 && _lovelaceDashbordUrl != HomeAssistant.DEFAULT_DASHBOARD) { + if (AppSettings().haVersion >= 107 && _lovelaceDashbordUrl != HomeAssistant.DEFAULT_DASHBOARD) { additionalData = { 'url_path': _lovelaceDashbordUrl }; diff --git a/lib/main.dart b/lib/main.dart index 6d45848..32cfa6c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -187,12 +187,11 @@ void main() async { }; WidgetsFlutterBinding.ensureInitialized(); - SharedPreferences prefs = await SharedPreferences.getInstance(); - AppTheme theme = AppTheme.values[prefs.getInt('app-theme') ?? AppTheme.defaultTheme.index]; + AppSettings().loadAppTheme(); runZoned(() { runApp(new HAClientApp( - theme: theme, + theme: AppSettings().appTheme, )); }, onError: (error, stack) { _reportError(error, stack); @@ -287,7 +286,7 @@ class _HAClientAppState extends State { "/quick-start": (context) => QuickStartPage(), "/haclient_zha": (context) => ZhaPage(), "/auth": (context) => new standaloneWebview.WebviewScaffold( - url: "${ConnectionManager().oauthUrl}", + url: "${AppSettings().oauthUrl}", appBar: new AppBar( leading: IconButton( icon: Icon(Icons.help), diff --git a/lib/managers/app_settings.dart b/lib/managers/app_settings.dart index 27d149e..bb7fa65 100644 --- a/lib/managers/app_settings.dart +++ b/lib/managers/app_settings.dart @@ -16,15 +16,25 @@ class AppSettings { String displayHostname; String webSocketAPIEndpoint; String httpWebHost; - String _token; - String _tempToken; + String longLivedToken; + String tempToken; String oauthUrl; String webhookId; double haVersion; bool scrollBadges; int appIntegrationVersion; + AppTheme appTheme; + final int defaultLocationUpdateIntervalMinutes = 20; + Duration locationUpdateInterval; + bool locationTrackingEnabled = false; - bool get isAuthenticated => _token != null; + bool get isAuthenticated => longLivedToken != null; + bool get isTempAuthenticated => tempToken != null; + + loadAppTheme() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + appTheme = AppTheme.values[prefs.getInt('app-theme') ?? AppTheme.defaultTheme.index]; + } Future load(bool quick) async { if (!quick) { @@ -36,13 +46,16 @@ class AppSettings { appIntegrationVersion = prefs.getInt('app-integration-version') ?? 0; scrollBadges = prefs.getBool('scroll-badges') ?? true; displayHostname = "$_domain:$_port"; - _webSocketAPIEndpoint = + webSocketAPIEndpoint = "${prefs.getString('hassio-protocol')}://$_domain:$_port/api/websocket"; httpWebHost = "${prefs.getString('hassio-res-protocol')}://$_domain:$_port"; + locationUpdateInterval = Duration(minutes: prefs.getInt("location-interval") ?? + defaultLocationUpdateIntervalMinutes); + locationTrackingEnabled = prefs.getBool("location-enabled") ?? false; try { final storage = new FlutterSecureStorage(); - _token = await storage.read(key: "hacl_llt"); + longLivedToken = await storage.read(key: "hacl_llt"); Logger.d("Long-lived token read successful"); oauthUrl = "$httpWebHost/auth/authorize?client_id=${Uri.encodeComponent( 'https://ha-client.app')}&redirect_uri=${Uri @@ -54,15 +67,58 @@ class AppSettings { } } + Future save(Map settings) async { + if (settings != null && settings.isNotEmpty) { + SharedPreferences prefs = await SharedPreferences.getInstance(); + settings.forEach((k,v) async { + if (v is String) { + await prefs.setString(k, v); + } else if (v is bool) { + await prefs.setBool(k ,v); + } else if (v is int) { + await prefs.setInt(k ,v); + } else if (v is double) { + await prefs.setDouble(k, v); + } else { + Logger.e('Unknown setting type: <$k, $v>'); + } + }); + } + } + Future startAuth() { return AuthManager().start( oauthUrl: oauthUrl ).then((token) { Logger.d("Token from AuthManager recived"); - _tempToken = token; + tempToken = token; }); } + Future clearTokens() async { + longLivedToken = null; + tempToken = null; + try { + final storage = new FlutterSecureStorage(); + await storage.delete(key: "hacl_llt"); + } catch(e, stacktrace) { + Logger.e("Error clearing tokens: $e", stacktrace: stacktrace); + } + } + + Future saveLongLivedToken(token) async { + longLivedToken = token; + tempToken = null; + try { + final storage = new FlutterSecureStorage(); + await storage.write(key: "hacl_llt", value: "$longLivedToken"); + SharedPreferences prefs = await SharedPreferences.getInstance(); + prefs.setBool("oauth-used", true); + } catch(e, stacktrace) { + Logger.e("Error saving long-lived token: $e", stacktrace: stacktrace); + } + } + bool isNotConfigured() { return _domain == null && _port == null && webhookId == null && mobileAppDeviceName == null; } diff --git a/lib/managers/connection_manager.class.dart b/lib/managers/connection_manager.class.dart index 85ed2a5..e7283a6 100644 --- a/lib/managers/connection_manager.class.dart +++ b/lib/managers/connection_manager.class.dart @@ -212,16 +212,16 @@ class ConnectionManager { Logger.d( "[Sending] ==> auth request"); sendSocketMessage( type: "auth", - additionalData: {"access_token": "$_token"}, + additionalData: {"access_token": "${AppSettings().longLivedToken}"}, auth: true ).then((_) { completer.complete(); }).catchError((e) => completer.completeError(e)); - } else if (_tempToken != null) { + } else if (AppSettings().isTempAuthenticated != null) { Logger.d("We have temp token. Loging in..."); sendSocketMessage( type: "auth", - additionalData: {"access_token": "$_tempToken"}, + additionalData: {"access_token": "${AppSettings().tempToken}"}, auth: true ).then((_) { Logger.d("Requesting long-lived token..."); @@ -239,35 +239,17 @@ class ConnectionManager { return completer.future; } - Future logout() { + Future logout() async { Logger.d("Logging out"); - Completer completer = Completer(); - _disconnect().whenComplete(() { - _token = null; - _tempToken = null; - final storage = new FlutterSecureStorage(); - storage.delete(key: "hacl_llt").whenComplete((){ - completer.complete(); - }); - }); - return completer.future; + await _disconnect(); + await AppSettings().clearTokens(); } Future _getLongLivedToken() { Completer completer = Completer(); sendSocketMessage(type: "auth/long_lived_access_token", additionalData: {"client_name": "HA Client app ${DateTime.now().millisecondsSinceEpoch}", "lifespan": 365}).then((data) { Logger.d("Got long-lived token."); - _token = data; - _tempToken = null; - final storage = new FlutterSecureStorage(); - storage.write(key: "hacl_llt", value: "$_token").then((_) { - SharedPreferences.getInstance().then((prefs) { - prefs.setBool("oauth-used", true); - completer.complete(); - }); - }).catchError((e) { - throw e; - }); + AppSettings().saveLongLivedToken(data); }).catchError((e) { completer.completeError(HACException("Authentication error: $e", actions: [HAErrorAction.reload(title: "Retry"), HAErrorAction.loginAgain(title: "Relogin")])); }); @@ -339,11 +321,11 @@ class ConnectionManager { DateTime now = DateTime.now(); //String endTime = formatDate(now, [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]); String startTime = formatDate(now.subtract(Duration(hours: 24)), [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]); - String url = "$httpWebHost/api/history/period/$startTime?&filter_entity_id=$entityId"; + String url = "${AppSettings().httpWebHost}/api/history/period/$startTime?&filter_entity_id=$entityId"; Logger.d("[Sending] ==> HTTP /api/history/period/$startTime?&filter_entity_id=$entityId"); http.Response historyResponse; historyResponse = await http.get(url, headers: { - "authorization": "Bearer $_token", + "authorization": "Bearer ${AppSettings().longLivedToken}", "Content-Type": "application/json" }); var history = json.decode(historyResponse.body); @@ -357,14 +339,14 @@ class ConnectionManager { Future sendHTTPPost({String endPoint, String data, String contentType: "application/json", bool includeAuthHeader: true}) async { Completer completer = Completer(); - String url = "$httpWebHost$endPoint"; + String url = "${AppSettings().httpWebHost}$endPoint"; Logger.d("[Sending] ==> HTTP $endPoint"); Map headers = {}; if (contentType != null) { headers["Content-Type"] = contentType; } if (includeAuthHeader) { - headers["authorization"] = "Bearer $_token"; + headers["authorization"] = "Bearer ${AppSettings().longLivedToken}"; } http.post( url, diff --git a/lib/managers/location_manager.class.dart b/lib/managers/location_manager.class.dart index e0563d0..8bc6522 100644 --- a/lib/managers/location_manager.class.dart +++ b/lib/managers/location_manager.class.dart @@ -13,68 +13,53 @@ class LocationManager { init(); } - final int defaultUpdateIntervalMinutes = 20; final String backgroundTaskId = "haclocationtask0"; final String backgroundTaskTag = "haclocation"; - Duration _updateInterval; - bool _isRunning; void init() async { - SharedPreferences prefs = await SharedPreferences.getInstance(); - await prefs.reload(); - _updateInterval = Duration(minutes: prefs.getInt("location-interval") ?? - defaultUpdateIntervalMinutes); - _isRunning = prefs.getBool("location-enabled") ?? false; - if (_isRunning) { + if (AppSettings().locationTrackingEnabled) { await _startLocationService(); } } setSettings(bool enabled, int interval) async { - SharedPreferences prefs = await SharedPreferences.getInstance(); - if (interval != _updateInterval.inMinutes) { - prefs.setInt("location-interval", interval); - _updateInterval = Duration(minutes: interval); - if (_isRunning) { - Logger.d("Stopping location tracking..."); - _isRunning = false; - await _stopLocationService(); - } + if (interval != AppSettings().locationUpdateInterval.inMinutes) { + await _stopLocationService(); } - if (enabled && !_isRunning) { + AppSettings().save({ + 'location-interval': interval, + 'location-enabled': enabled + }); + AppSettings().locationUpdateInterval = Duration(minutes: interval); + AppSettings().locationTrackingEnabled = enabled; + if (enabled && !AppSettings().locationTrackingEnabled) { Logger.d("Starting location tracking"); - SharedPreferences prefs = await SharedPreferences.getInstance(); - prefs.setBool("location-enabled", enabled); - _isRunning = true; await _startLocationService(); - } else if (!enabled && _isRunning) { + } else if (!enabled && AppSettings().locationTrackingEnabled) { Logger.d("Stopping location tracking..."); - SharedPreferences prefs = await SharedPreferences.getInstance(); - prefs.setBool("location-enabled", enabled); - _isRunning = false; await _stopLocationService(); } } _startLocationService() async { - String webhookId = ConnectionManager().webhookId; - String httpWebHost = ConnectionManager().httpWebHost; + String webhookId = AppSettings().webhookId; + String httpWebHost = AppSettings().httpWebHost; if (webhookId != null && webhookId.isNotEmpty) { Duration interval; int delayFactor; int taskCount; - Logger.d("Starting location update for every ${_updateInterval + Logger.d("Starting location update for every ${AppSettings().locationUpdateInterval .inMinutes} minutes..."); - if (_updateInterval.inMinutes == 10) { + if (AppSettings().locationUpdateInterval.inMinutes == 10) { interval = Duration(minutes: 20); taskCount = 2; delayFactor = 10; - } else if (_updateInterval.inMinutes == 5) { + } else if (AppSettings().locationUpdateInterval.inMinutes == 5) { interval = Duration(minutes: 15); taskCount = 3; delayFactor = 5; } else { - interval = _updateInterval; + interval = AppSettings().locationUpdateInterval; taskCount = 1; delayFactor = 0; } @@ -112,8 +97,8 @@ class LocationManager { Logger.d("[Foreground location] Started"); Geolocator geolocator = Geolocator(); var battery = Battery(); - String webhookId = ConnectionManager().webhookId; - String httpWebHost = ConnectionManager().httpWebHost; + String webhookId = AppSettings().webhookId; + String httpWebHost = AppSettings().httpWebHost; if (webhookId != null && webhookId.isNotEmpty) { Logger.d("[Foreground location] Getting battery level..."); int batteryLevel = await battery.batteryLevel; diff --git a/lib/managers/mobile_app_integration_manager.class.dart b/lib/managers/mobile_app_integration_manager.class.dart index 94dcddf..2fc2e11 100644 --- a/lib/managers/mobile_app_integration_manager.class.dart +++ b/lib/managers/mobile_app_integration_manager.class.dart @@ -25,9 +25,9 @@ class MobileAppIntegrationManager { static Future checkAppRegistration() { Completer completer = Completer(); - _appRegistrationData["device_name"] = ConnectionManager().mobileAppDeviceName ?? getDefaultDeviceName(); + _appRegistrationData["device_name"] = AppSettings().mobileAppDeviceName ?? getDefaultDeviceName(); (_appRegistrationData["app_data"] as Map)["push_token"] = "${HomeAssistant().fcmToken}"; - if (ConnectionManager().webhookId == null) { + if (AppSettings().webhookId == null) { Logger.d("Mobile app was not registered yet. Registering..."); var registrationData = Map.from(_appRegistrationData); registrationData.addAll({ @@ -36,7 +36,7 @@ class MobileAppIntegrationManager { "os_name": DeviceInfoManager().osName, "supports_encryption": false, }); - if (ConnectionManager().haVersion >= 104) { + if (AppSettings().haVersion >= 104) { registrationData.addAll({ "device_id": "${DeviceInfoManager().unicDeviceId}" }); @@ -48,12 +48,12 @@ class MobileAppIntegrationManager { ).then((response) { Logger.d("Processing registration responce..."); var responseObject = json.decode(response); - ConnectionManager().webhookId = responseObject["webhook_id"]; - ConnectionManager().appIntegrationVersion = INTEGRATION_VERSION; - SharedPreferences.getInstance().then((prefs) { - prefs.setString("app-webhook-id", responseObject["webhook_id"]); - prefs.setInt('app-integration-version', INTEGRATION_VERSION); - + AppSettings().webhookId = responseObject["webhook_id"]; + AppSettings().appIntegrationVersion = INTEGRATION_VERSION; + AppSettings().save({ + 'app-webhook-id': responseObject["webhook_id"], + 'app-integration-version': INTEGRATION_VERSION + }).then((prefs) { completer.complete(); eventBus.fire(ShowPopupEvent( popup: Popup( @@ -84,7 +84,7 @@ class MobileAppIntegrationManager { "data": _appRegistrationData }; ConnectionManager().sendHTTPPost( - endPoint: "/api/webhook/${ConnectionManager().webhookId}", + endPoint: "/api/webhook/${AppSettings().webhookId}", includeAuthHeader: false, data: json.encode(updateData) ).then((response) { @@ -98,7 +98,7 @@ class MobileAppIntegrationManager { Logger.w("No registration data in response. MobileApp integration was removed or broken"); _askToRegisterApp(); } else { - if (INTEGRATION_VERSION > ConnectionManager().appIntegrationVersion) { + if (INTEGRATION_VERSION > AppSettings().appIntegrationVersion) { Logger.d('App registration needs to be updated'); _askToRemoveAndRegisterApp(); } else { diff --git a/lib/pages/main/main.page.dart b/lib/pages/main/main.page.dart index d1a47f1..73df13a 100644 --- a/lib/pages/main/main.page.dart +++ b/lib/pages/main/main.page.dart @@ -246,7 +246,7 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker void _showOAuth() { _preventAppRefresh = true; - Navigator.of(context).pushNamed("/auth", arguments: {"url": ConnectionManager().oauthUrl}); + Navigator.of(context).pushNamed("/auth", arguments: {"url": AppSettings().oauthUrl}); } _setErrorState(HACException e) { @@ -463,7 +463,7 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker child: new Text("Reload"), value: "reload", )); - if (ConnectionManager().isAuthenticated) { + if (AppSettings().isAuthenticated) { _showLoginButton = false; serviceMenuItems.add( PopupMenuItem( diff --git a/lib/pages/settings/app_settings.page.dart b/lib/pages/settings/app_settings.page.dart index 5503d06..d4c68b9 100644 --- a/lib/pages/settings/app_settings.page.dart +++ b/lib/pages/settings/app_settings.page.dart @@ -39,7 +39,7 @@ class _AppSettingsPageState extends State { _buildMenuItem(context, MaterialDesignIcons.getIconDataFromIconName('mdi:network'), 'Connection settings', AppSettingsSection.connectionSettings), _buildMenuItem(context, MaterialDesignIcons.getIconDataFromIconName('mdi:brush'), 'Look and feel', AppSettingsSection.lookAndFeel), ]; - if (ConnectionManager().webhookId != null) { + if (AppSettings().webhookId != null) { items.insert(1, _buildMenuItem(context, MaterialDesignIcons.getIconDataFromIconName('mdi:cellphone-android'), 'Integration settings', AppSettingsSection.integrationSettings)); } return ListView( diff --git a/lib/pages/settings/connection_settings.part.dart b/lib/pages/settings/connection_settings.part.dart index 75101dc..2f50826 100644 --- a/lib/pages/settings/connection_settings.part.dart +++ b/lib/pages/settings/connection_settings.part.dart @@ -31,7 +31,7 @@ class _ConnectionSettingsPageState extends State { } _loadSettings() async { - _includeDeviceName = widget.quickStart || ConnectionManager().webhookId == null; + _includeDeviceName = widget.quickStart || AppSettings().webhookId == null; SharedPreferences prefs = await SharedPreferences.getInstance(); String domain = prefs.getString('hassio-domain')?? ''; String port = prefs.getString('hassio-port') ?? ''; diff --git a/lib/pages/settings/integration_settings.part.dart b/lib/pages/settings/integration_settings.part.dart index bb1d1f2..e45ae0d 100644 --- a/lib/pages/settings/integration_settings.part.dart +++ b/lib/pages/settings/integration_settings.part.dart @@ -11,7 +11,7 @@ class IntegrationSettingsPage extends StatefulWidget { class _IntegrationSettingsPageState extends State { - int _locationInterval = LocationManager().defaultUpdateIntervalMinutes; + int _locationInterval = AppSettings().defaultLocationUpdateIntervalMinutes; bool _locationTrackingEnabled = false; bool _wait = false; @@ -28,7 +28,8 @@ class _IntegrationSettingsPageState extends State { SharedPreferences.getInstance().then((prefs) { setState(() { _locationTrackingEnabled = prefs.getBool("location-enabled") ?? false; - _locationInterval = prefs.getInt("location-interval") ?? LocationManager().defaultUpdateIntervalMinutes; + _locationInterval = prefs.getInt("location-interval") ?? + AppSettings().defaultLocationUpdateIntervalMinutes; if (_locationInterval % 5 != 0) { _locationInterval = 5 * (_locationInterval ~/ 5); } diff --git a/lib/pages/settings/lookandfeel_settings.part.dart b/lib/pages/settings/lookandfeel_settings.part.dart index 230bba6..aee37a9 100644 --- a/lib/pages/settings/lookandfeel_settings.part.dart +++ b/lib/pages/settings/lookandfeel_settings.part.dart @@ -44,7 +44,7 @@ class _LookAndFeelSettingsPageState extends State { Future _saveOther() async { SharedPreferences prefs = await SharedPreferences.getInstance(); - ConnectionManager().scrollBadges = _scrollBadges; + AppSettings().scrollBadges = _scrollBadges; await prefs.setBool('scroll-badges', _scrollBadges); } diff --git a/lib/panels/config_panel_widget.dart b/lib/panels/config_panel_widget.dart index 05b8524..58dfb45 100644 --- a/lib/panels/config_panel_widget.dart +++ b/lib/panels/config_panel_widget.dart @@ -20,7 +20,7 @@ class _ConfigPanelWidgetState extends State { Widget build(BuildContext context) { return ListView( children: [ - LinkToWebConfig(name: "Home Assistant configuration", url: ConnectionManager().httpWebHost+"/config"), + LinkToWebConfig(name: "Home Assistant configuration", url: AppSettings().httpWebHost+"/config"), ], ); } diff --git a/lib/panels/panel_class.dart b/lib/panels/panel_class.dart index 1ec6041..11fca58 100644 --- a/lib/panels/panel_class.dart +++ b/lib/panels/panel_class.dart @@ -38,7 +38,7 @@ class Panel { eventBus.fire(ReloadUIEvent()); }); } else { - Launcher.launchAuthenticatedWebView(context: context, url: "${ConnectionManager().httpWebHost}/$urlPath", title: "${this.title}"); + Launcher.launchAuthenticatedWebView(context: context, url: "${AppSettings().httpWebHost}/$urlPath", title: "${this.title}"); } } diff --git a/lib/popups.dart b/lib/popups.dart index ff46fcc..f367225 100644 --- a/lib/popups.dart +++ b/lib/popups.dart @@ -153,14 +153,14 @@ class RegisterAppPopup extends Popup { Padding( padding: EdgeInsets.all(20), child: TextFormField( - initialValue: ConnectionManager().mobileAppDeviceName ?? MobileAppIntegrationManager.getDefaultDeviceName(), + initialValue: AppSettings().mobileAppDeviceName ?? MobileAppIntegrationManager.getDefaultDeviceName(), onSaved: (newValue) { String deviceName = newValue?.trim(); SharedPreferences.getInstance().then((prefs) { prefs.remove("app-webhook-id"); prefs.setString('app-integration-device-name', deviceName); - ConnectionManager().webhookId = null; - ConnectionManager().mobileAppDeviceName = deviceName; + AppSettings().webhookId = null; + AppSettings().mobileAppDeviceName = deviceName; Navigator.of(context).pop(); MobileAppIntegrationManager.checkAppRegistration(); }); diff --git a/lib/utils/launcher.dart b/lib/utils/launcher.dart index 4930904..a41827b 100644 --- a/lib/utils/launcher.dart +++ b/lib/utils/launcher.dart @@ -45,7 +45,7 @@ class Launcher { if (viewState.type == standaloneWebview.WebViewState.startLoad) { Logger.d("[WebView] Injecting external auth JS"); rootBundle.loadString('assets/js/externalAuth.js').then((js){ - flutterWebViewPlugin.evalJavascript(js.replaceFirst("[token]", ConnectionManager()._token)); + flutterWebViewPlugin.evalJavascript(js.replaceFirst("[token]", AppSettings().longLivedToken)); }); } });