WIP #355 Disconnect when logout

This commit is contained in:
estevez-dev 2019-04-05 13:06:14 +03:00
parent 15b3d31a6f
commit cabf836fa3
6 changed files with 28 additions and 33 deletions

View File

@ -250,10 +250,16 @@ class Connection {
} }
Future logout() { Future logout() {
_token = null; Completer completer = Completer();
_tempToken = null; _disconnect().whenComplete(() {
final storage = new FlutterSecureStorage(); _token = null;
return storage.delete(key: "hacl_llt"); _tempToken = null;
final storage = new FlutterSecureStorage();
storage.delete(key: "hacl_llt").whenComplete((){
completer.complete();
});
});
return completer.future;
} }
Future _getLongLivedToken() { Future _getLongLivedToken() {

View File

@ -131,7 +131,7 @@ class _CameraStreamViewState extends State<CameraStreamView> {
.of(context) .of(context)
.entityWrapper .entityWrapper
.entity; .entity;
_webHost = HomeAssistantModel.of(context).homeAssistant.connection.httpWebHost; _webHost = Connection().httpWebHost;
_connect(); _connect();
} }

View File

@ -40,14 +40,14 @@ class _EntityHistoryWidgetState extends State<EntityHistoryWidget> {
_needToUpdateHistory = true; _needToUpdateHistory = true;
} }
void _loadHistory(HomeAssistant ha, String entityId) { void _loadHistory(String entityId) {
DateTime now = DateTime.now(); DateTime now = DateTime.now();
if (_historyLastUpdated != null) { if (_historyLastUpdated != null) {
Logger.d("History was updated ${now.difference(_historyLastUpdated).inSeconds} seconds ago"); Logger.d("History was updated ${now.difference(_historyLastUpdated).inSeconds} seconds ago");
} }
if (_historyLastUpdated == null || now.difference(_historyLastUpdated).inSeconds > 30) { if (_historyLastUpdated == null || now.difference(_historyLastUpdated).inSeconds > 30) {
_historyLastUpdated = now; _historyLastUpdated = now;
ha.connection.getHistory(entityId).then((history){ Connection().getHistory(entityId).then((history){
if (!_disposed) { if (!_disposed) {
setState(() { setState(() {
_history = history.isNotEmpty ? history[0] : []; _history = history.isNotEmpty ? history[0] : [];
@ -68,13 +68,12 @@ class _EntityHistoryWidgetState extends State<EntityHistoryWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final HomeAssistantModel homeAssistantModel = HomeAssistantModel.of(context);
final EntityModel entityModel = EntityModel.of(context); final EntityModel entityModel = EntityModel.of(context);
final Entity entity = entityModel.entityWrapper.entity; final Entity entity = entityModel.entityWrapper.entity;
if (!_needToUpdateHistory) { if (!_needToUpdateHistory) {
_needToUpdateHistory = true; _needToUpdateHistory = true;
} else { } else {
_loadHistory(homeAssistantModel.homeAssistant, entity.entityId); _loadHistory(entity.entityId);
} }
return _buildChart(); return _buildChart();
} }

View File

@ -2,14 +2,6 @@ part of 'main.dart';
class HomeAssistant { class HomeAssistant {
final Connection connection = Connection();
//bool _useLovelace = false;
//bool isSettingsLoaded = false;
EntityCollection entities; EntityCollection entities;
HomeAssistantUI ui; HomeAssistantUI ui;
Map _instanceConfig = {}; Map _instanceConfig = {};
@ -33,7 +25,6 @@ class HomeAssistant {
String get userAvatarText => userName.length > 0 ? userName[0] : ""; String get userAvatarText => userName.length > 0 ? userName[0] : "";
bool get isNoEntities => entities == null || entities.isEmpty; bool get isNoEntities => entities == null || entities.isEmpty;
bool get isNoViews => ui == null || ui.isEmpty; bool get isNoViews => ui == null || ui.isEmpty;
//int get viewsCount => entities.views.length ?? 0;
HomeAssistant() { HomeAssistant() {
Connection().onStateChangeCallback = _handleEntityStateChange; Connection().onStateChangeCallback = _handleEntityStateChange;
@ -46,7 +37,7 @@ class HomeAssistant {
Logger.w("Previous data fetch is not completed yet"); Logger.w("Previous data fetch is not completed yet");
return _fetchCompleter.future; return _fetchCompleter.future;
} }
if (entities == null) entities = EntityCollection(connection.httpWebHost); if (entities == null) entities = EntityCollection(Connection().httpWebHost);
_fetchCompleter = Completer(); _fetchCompleter = Completer();
List<Future> futures = []; List<Future> futures = [];
futures.add(_getStates()); futures.add(_getStates());
@ -72,7 +63,7 @@ class HomeAssistant {
Future logout() async { Future logout() async {
Logger.d("Logging out..."); Logger.d("Logging out...");
await connection.logout().then((_) { await Connection().logout().then((_) {
ui?.clear(); ui?.clear();
entities?.clear(); entities?.clear();
panels?.clear(); panels?.clear();
@ -80,7 +71,7 @@ class HomeAssistant {
} }
Future _getConfig() async { Future _getConfig() async {
await connection.sendSocketMessage(type: "get_config").then((data) { await Connection().sendSocketMessage(type: "get_config").then((data) {
_instanceConfig = Map.from(data); _instanceConfig = Map.from(data);
}).catchError((e) { }).catchError((e) {
throw {"errorCode": 1, "errorMessage": "Error getting config: $e"}; throw {"errorCode": 1, "errorMessage": "Error getting config: $e"};
@ -88,7 +79,7 @@ class HomeAssistant {
} }
Future _getStates() async { Future _getStates() async {
await connection.sendSocketMessage(type: "get_states").then( await Connection().sendSocketMessage(type: "get_states").then(
(data) => entities.parse(data) (data) => entities.parse(data)
).catchError((e) { ).catchError((e) {
throw {"errorCode": 1, "errorMessage": "Error getting states: $e"}; throw {"errorCode": 1, "errorMessage": "Error getting states: $e"};
@ -96,27 +87,27 @@ class HomeAssistant {
} }
Future _getLovelace() async { Future _getLovelace() async {
await connection.sendSocketMessage(type: "lovelace/config").then((data) => _rawLovelaceData = data).catchError((e) { await Connection().sendSocketMessage(type: "lovelace/config").then((data) => _rawLovelaceData = data).catchError((e) {
throw {"errorCode": 1, "errorMessage": "Error getting lovelace config: $e"}; throw {"errorCode": 1, "errorMessage": "Error getting lovelace config: $e"};
}); });
} }
Future _getUserInfo() async { Future _getUserInfo() async {
_userName = null; _userName = null;
await connection.sendSocketMessage(type: "auth/current_user").then((data) => _userName = data["name"]).catchError((e) { await Connection().sendSocketMessage(type: "auth/current_user").then((data) => _userName = data["name"]).catchError((e) {
Logger.w("Can't get user info: ${e}"); Logger.w("Can't get user info: ${e}");
}); });
} }
Future _getServices() async { Future _getServices() async {
await connection.sendSocketMessage(type: "get_services").then((data) => Logger.d("Services received")).catchError((e) { await Connection().sendSocketMessage(type: "get_services").then((data) => Logger.d("Services received")).catchError((e) {
Logger.w("Can't get services: ${e}"); Logger.w("Can't get services: ${e}");
}); });
} }
Future _getPanels() async { Future _getPanels() async {
panels.clear(); panels.clear();
await connection.sendSocketMessage(type: "get_panels").then((data) { await Connection().sendSocketMessage(type: "get_panels").then((data) {
data.forEach((k,v) { data.forEach((k,v) {
String title = v['title'] == null ? "${k[0].toUpperCase()}${k.substring(1)}" : "${v['title'][0].toUpperCase()}${v['title'].substring(1)}"; String title = v['title'] == null ? "${k[0].toUpperCase()}${k.substring(1)}" : "${v['title'][0].toUpperCase()}${v['title'].substring(1)}";
panels.add(Panel( panels.add(Panel(

View File

@ -288,7 +288,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
_firebaseMessaging.getToken().then((String token) { _firebaseMessaging.getToken().then((String token) {
Logger.d("Device name: ${json.encode(Connection().deviceName)}"); Logger.d("Device name: ${json.encode(Connection().deviceName)}");
widget.homeAssistant.connection.sendHTTPPost( Connection().sendHTTPPost(
endPoint: '/api/notify.ha-client', endPoint: '/api/notify.ha-client',
data: '{"token": "$token", "device": ${json.encode(Connection().deviceName)}}' data: '{"token": "$token", "device": ${json.encode(Connection().deviceName)}}'
).then((_) { ).then((_) {
@ -310,7 +310,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => WebviewScaffold( builder: (context) => WebviewScaffold(
url: "${widget.homeAssistant.connection.oauthUrl}", url: "${Connection().oauthUrl}",
appBar: new AppBar( appBar: new AppBar(
leading: IconButton( leading: IconButton(
icon: Icon(Icons.help), icon: Icon(Icons.help),
@ -342,7 +342,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
message: "Calling $domain.$service", message: "Calling $domain.$service",
duration: Duration(seconds: 3) duration: Duration(seconds: 3)
); );
widget.homeAssistant.connection.callService(domain: domain, service: service, entityId: entityId, additionalServiceData: additionalParams).catchError((e) => _setErrorState(e)); Connection().callService(domain: domain, service: service, entityId: entityId, additionalServiceData: additionalParams).catchError((e) => _setErrorState(e));
} }
void _showEntityPage(String entityId) { void _showEntityPage(String entityId) {
@ -405,7 +405,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
new ListTile( new ListTile(
leading: Icon(MaterialDesignIcons.getIconDataFromIconName("mdi:home-assistant")), leading: Icon(MaterialDesignIcons.getIconDataFromIconName("mdi:home-assistant")),
title: Text("Open Web UI"), title: Text("Open Web UI"),
onTap: () => HAUtils.launchURL(widget.homeAssistant.connection.httpWebHost), onTap: () => HAUtils.launchURL(Connection().httpWebHost),
) )
); );
menuItems.addAll([ menuItems.addAll([
@ -647,7 +647,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
child: new Text("Reload"), child: new Text("Reload"),
value: "reload", value: "reload",
)); ));
if (widget.homeAssistant.connection.isAuthenticated) { if (Connection().isAuthenticated) {
popupMenuItems.add( popupMenuItems.add(
PopupMenuItem<String>( PopupMenuItem<String>(
child: new Text("Logout"), child: new Text("Logout"),

View File

@ -36,8 +36,7 @@ class Panel {
) )
); );
} else { } else {
HomeAssistantModel haModel = HomeAssistantModel.of(context); String url = "${Connection().httpWebHost}/$urlPath";
String url = "${haModel.homeAssistant.connection.httpWebHost}/$urlPath";
Logger.d("Launching custom tab with $url"); Logger.d("Launching custom tab with $url");
HAUtils.launchURLInCustomTab(context, url); HAUtils.launchURLInCustomTab(context, url);
} }