defer fcm token load

This commit is contained in:
Yegor Vialov 2020-05-25 11:58:14 +00:00
parent 141a68faf7
commit 4493975676
3 changed files with 92 additions and 88 deletions

View File

@ -35,7 +35,7 @@ public class MainActivity extends FlutterActivity {
Context context = getActivity(); Context context = getActivity();
SharedPreferences.Editor editor = context.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE).edit(); SharedPreferences.Editor editor = context.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE).edit();
String token = task.getResult().getToken(); String token = task.getResult().getToken();
editor.putString("flutter.fcm-token", token); editor.putString("flutter.push-token", token);
editor.commit(); editor.commit();
} }
} }

View File

@ -20,7 +20,6 @@ class AppSettings {
String tempToken; String tempToken;
String oauthUrl; String oauthUrl;
String webhookId; String webhookId;
String fcmToken;
double haVersion; double haVersion;
bool scrollBadges; bool scrollBadges;
AppTheme appTheme; AppTheme appTheme;
@ -40,7 +39,6 @@ class AppSettings {
if (full) { if (full) {
Logger.d('Loading settings...'); Logger.d('Loading settings...');
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
fcmToken = prefs.getString('fcm-token');
_domain = prefs.getString('hassio-domain'); _domain = prefs.getString('hassio-domain');
_port = prefs.getString('hassio-port'); _port = prefs.getString('hassio-port');
webhookId = prefs.getString('app-webhook-id'); webhookId = prefs.getString('app-webhook-id');
@ -69,6 +67,11 @@ class AppSettings {
} }
} }
Future<dynamic> loadSingle(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.get('$key');
}
Future save(Map<String, dynamic> settings) async { Future save(Map<String, dynamic> settings) async {
if (settings != null && settings.isNotEmpty) { if (settings != null && settings.isNotEmpty) {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();

View File

@ -24,94 +24,95 @@ class MobileAppIntegrationManager {
static Future checkAppRegistration() { static Future checkAppRegistration() {
Completer completer = Completer(); Completer completer = Completer();
_appRegistrationData["device_name"] = AppSettings().mobileAppDeviceName ?? getDefaultDeviceName(); _appRegistrationData["device_name"] = AppSettings().mobileAppDeviceName ?? getDefaultDeviceName();
(_appRegistrationData["app_data"] as Map)["push_token"] = "${AppSettings().fcmToken}"; AppSettings().loadSingle('push-token').then((fcmToken) {
if (AppSettings().webhookId == null) { (_appRegistrationData["app_data"] as Map)["push_token"] = "$fcmToken";
Logger.d("Mobile app was not registered yet. Registering..."); if (AppSettings().webhookId == null) {
var registrationData = Map.from(_appRegistrationData); Logger.d("Mobile app was not registered yet. Registering...");
registrationData.addAll({ var registrationData = Map.from(_appRegistrationData);
"app_id": "ha_client",
"app_name": "$appName",
"os_name": DeviceInfoManager().osName,
"supports_encryption": false,
});
if (AppSettings().haVersion >= 104) {
registrationData.addAll({ registrationData.addAll({
"device_id": "${DeviceInfoManager().unicDeviceId}" "app_id": "ha_client",
"app_name": "$appName",
"os_name": DeviceInfoManager().osName,
"supports_encryption": false,
});
if (AppSettings().haVersion >= 104) {
registrationData.addAll({
"device_id": "${DeviceInfoManager().unicDeviceId}"
});
}
ConnectionManager().sendHTTPPost(
endPoint: "/api/mobile_app/registrations",
includeAuthHeader: true,
data: json.encode(registrationData)
).then((response) {
Logger.d("Processing registration responce...");
var responseObject = json.decode(response);
AppSettings().webhookId = responseObject["webhook_id"];
AppSettings().save({
'app-webhook-id': responseObject["webhook_id"]
}).then((prefs) {
completer.complete();
eventBus.fire(ShowPopupEvent(
popup: Popup(
title: "Mobile app Integration was created",
body: "HA Client was registered as MobileApp in your Home Assistant. To start using notifications you need to restart your Home Assistant",
positiveText: "Restart now",
negativeText: "Later",
onPositive: () {
ConnectionManager().callService(domain: "homeassistant", service: "restart");
},
)
));
});
}).catchError((e) {
completer.complete();
if (e is http.Response) {
Logger.e("Error registering the app: ${e.statusCode}: ${e.body}");
} else {
Logger.e("Error registering the app: ${e?.toString()}");
}
_showError();
});
} else {
Logger.d("App was previously registered. Checking...");
var updateData = {
"type": "update_registration",
"data": _appRegistrationData
};
ConnectionManager().sendHTTPPost(
endPoint: "/api/webhook/${AppSettings().webhookId}",
includeAuthHeader: false,
data: json.encode(updateData)
).then((response) {
var registrationData;
try {
registrationData = json.decode(response);
} catch (e) {
registrationData = null;
}
if (registrationData == null || registrationData.isEmpty) {
Logger.w("No registration data in response. MobileApp integration was removed or broken");
_askToRegisterApp();
} else {
Logger.d('App registration works fine');
}
completer.complete();
}).catchError((e) {
if (e is http.Response && e.statusCode == 410) {
Logger.w("MobileApp integration was removed");
_askToRegisterApp();
} else if (e is http.Response) {
Logger.w("Error updating app registration: ${e.statusCode}: ${e.body}");
_showError();
} else {
Logger.w("Error updating app registration: ${e?.toString()}");
_showError();
}
completer.complete();
}); });
} }
ConnectionManager().sendHTTPPost( });
endPoint: "/api/mobile_app/registrations", return completer.future;
includeAuthHeader: true,
data: json.encode(registrationData)
).then((response) {
Logger.d("Processing registration responce...");
var responseObject = json.decode(response);
AppSettings().webhookId = responseObject["webhook_id"];
AppSettings().save({
'app-webhook-id': responseObject["webhook_id"]
}).then((prefs) {
completer.complete();
eventBus.fire(ShowPopupEvent(
popup: Popup(
title: "Mobile app Integration was created",
body: "HA Client was registered as MobileApp in your Home Assistant. To start using notifications you need to restart your Home Assistant",
positiveText: "Restart now",
negativeText: "Later",
onPositive: () {
ConnectionManager().callService(domain: "homeassistant", service: "restart");
},
)
));
});
}).catchError((e) {
completer.complete();
if (e is http.Response) {
Logger.e("Error registering the app: ${e.statusCode}: ${e.body}");
} else {
Logger.e("Error registering the app: ${e?.toString()}");
}
_showError();
});
return completer.future;
} else {
Logger.d("App was previously registered. Checking...");
var updateData = {
"type": "update_registration",
"data": _appRegistrationData
};
ConnectionManager().sendHTTPPost(
endPoint: "/api/webhook/${AppSettings().webhookId}",
includeAuthHeader: false,
data: json.encode(updateData)
).then((response) {
var registrationData;
try {
registrationData = json.decode(response);
} catch (e) {
registrationData = null;
}
if (registrationData == null || registrationData.isEmpty) {
Logger.w("No registration data in response. MobileApp integration was removed or broken");
_askToRegisterApp();
} else {
Logger.d('App registration works fine');
}
completer.complete();
}).catchError((e) {
if (e is http.Response && e.statusCode == 410) {
Logger.w("MobileApp integration was removed");
_askToRegisterApp();
} else if (e is http.Response) {
Logger.w("Error updating app registration: ${e.statusCode}: ${e.body}");
_showError();
} else {
Logger.w("Error updating app registration: ${e?.toString()}");
_showError();
}
completer.complete();
});
return completer.future;
}
} }
static void _showError() { static void _showError() {