Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Moved legacy app to separate folder. Added Generic Android app

Michael Rademaker3f7463abfcb9
diff --git a/console/android/.buildignore b/console/android/.buildignore
deleted file mode 100644
index 5322bb279..000000000
--- a/console/android/.buildignore
+++ /dev/null
@@ -1 +0,0 @@
-# Ignore this project in composite/superproject build
\ No newline at end of file
diff --git a/console/android/GenericApp/app/build.gradle b/console/android/GenericApp/app/build.gradle
new file mode 100644
index 000000000..b6387cd07
--- /dev/null
+++ b/console/android/GenericApp/app/build.gradle
@@ -0,0 +1,50 @@
+apply plugin: 'com.android.application'
+apply plugin: 'kotlin-android'
+apply plugin: 'kotlin-android-extensions'
+apply plugin: 'com.google.gms.google-services'
+
+android {
+ compileSdkVersion 29
+ buildToolsVersion "29.0.3"
+
+ defaultConfig {
+ applicationId "io.openremote.app"
+ minSdkVersion 25
+ targetSdkVersion 29
+ versionCode 17
+ versionName "1.0.2"
+
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+
+ resValue "string", "NOTIFICATION_CHANNEL_ID", applicationId + ".ORAppMessage"
+ }
+
+
+
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+}
+
+dependencies {
+ implementation fileTree(dir: "libs", include: ["*.jar"])
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
+ implementation 'androidx.core:core-ktx:1.3.2'
+ implementation 'androidx.appcompat:appcompat:1.2.0'
+ implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
+ implementation 'androidx.preference:preference:1.1.1'
+ implementation "com.google.android.gms:play-services-location:17.1.0"
+ implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8"
+
+ implementation platform('com.google.firebase:firebase-bom:26.0.0')
+ implementation 'com.google.firebase:firebase-messaging-ktx'
+ implementation 'com.google.android.material:material:1.2.1'
+}
\ No newline at end of file
diff --git a/console/android/GenericApp/app/google-services.json b/console/android/GenericApp/app/google-services.json
new file mode 100644
index 000000000..8880fd56a
--- /dev/null
+++ b/console/android/GenericApp/app/google-services.json
@@ -0,0 +1,47 @@
+{
+ "project_info": {
+ "project_number": "667022545910",
+ "firebase_url": "https://openremoteapp-a6a60.firebaseio.com",
+ "project_id": "openremoteapp-a6a60",
+ "storage_bucket": "openremoteapp-a6a60.appspot.com"
+ },
+ "client": [
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:667022545910:android:23c352988b6d3d6ea5add7",
+ "android_client_info": {
+ "package_name": "io.openremote.app"
+ }
+ },
+ "oauth_client": [
+ {
+ "client_id": "667022545910-g53k1fiocps3sso32hqvotr34fe2libr.apps.googleusercontent.com",
+ "client_type": 3
+ }
+ ],
+ "api_key": [
+ {
+ "current_key": "AIzaSyCXUqMM_P0Vo_pGmebCLgyD8RWeSN71TxU"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": [
+ {
+ "client_id": "667022545910-g53k1fiocps3sso32hqvotr34fe2libr.apps.googleusercontent.com",
+ "client_type": 3
+ },
+ {
+ "client_id": "667022545910-9fee9uvb8iguprjtimmq8uea6cqt2p5i.apps.googleusercontent.com",
+ "client_type": 2,
+ "ios_info": {
+ "bundle_id": "io.openremote.app"
+ }
+ }
+ ]
+ }
+ }
+ }
+ ],
+ "configuration_version": "1"
+}
\ No newline at end of file
diff --git a/console/android/GenericApp/app/proguard-rules.pro b/console/android/GenericApp/app/proguard-rules.pro
new file mode 100644
index 000000000..481bb4348
--- /dev/null
+++ b/console/android/GenericApp/app/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/AndroidManifest.xml b/console/android/GenericApp/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..e48ffe70b
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/AndroidManifest.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="io.openremote.app">
+
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:roundIcon="@mipmap/ic_launcher_round"
+ android:supportsRtl="true"
+ android:theme="@style/AppTheme">
+
+ <meta-data
+ android:name="com.google.firebase.messaging.default_notification_icon"
+ android:resource="@drawable/ic_notification" />
+ <meta-data
+ android:name="com.google.firebase.messaging.default_notification_color"
+ android:resource="@color/medium_green" />
+ <meta-data
+ android:name="com.google.firebase.messaging.default_notification_channel_id"
+ android:value="@string/NOTIFICATION_CHANNEL_ID" />
+
+ <activity
+ android:name=".ui.SplashActivity"
+ android:exported="true"
+ android:label="@string/app_name">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+
+ <meta-data
+ android:name="android.app.shortcuts"
+ android:resource="@xml/shortcuts" />
+ </activity>
+ <activity
+ android:name=".ui.ProjectActivity"
+ android:label="@string/title_activity_project"
+ android:exported="true">
+ </activity>
+ <activity android:name=".ui.MainActivity" />
+
+ <service android:name="io.openremote.app.service.ORFirebaseMessagingService">
+ <intent-filter>
+ <action android:name="com.google.firebase.MESSAGING_EVENT" />
+ </intent-filter>
+ </service>
+
+ <service android:name="io.openremote.app.service.ORMessagingActionService">
+
+ </service>
+
+ <receiver android:name=".service.GeofenceBootCompleteReceiver">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
+ </receiver>
+
+ <receiver
+ android:name=".service.GeofenceTransitionsIntentService"
+ android:enabled="true"
+ android:exported="true" />
+
+ </application>
+
+</manifest>
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/ic_launcher-playstore.png b/console/android/GenericApp/app/src/main/ic_launcher-playstore.png
new file mode 100644
index 000000000..4061aa956
Binary files /dev/null and b/console/android/GenericApp/app/src/main/ic_launcher-playstore.png differ
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAlertAction.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAlertAction.kt
new file mode 100644
index 000000000..c99967be8
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAlertAction.kt
@@ -0,0 +1,9 @@
+package io.openremote.app.models
+
+data class ORAlertAction(
+ val url: String,
+ val httpMethod: String = "GET",
+ val data: Map<String, Any>?,
+ val isSilent: Boolean = false,
+ val isOpenInBrowser: Boolean = false,
+)
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAlertButton.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAlertButton.kt
new file mode 100644
index 000000000..f6e833984
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAlertButton.kt
@@ -0,0 +1,6 @@
+package io.openremote.app.models
+
+data class ORAlertButton(
+ val title: String?,
+ val action: ORAlertAction?
+)
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAppConfig.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAppConfig.kt
new file mode 100644
index 000000000..d58a1fe22
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORAppConfig.kt
@@ -0,0 +1,14 @@
+package io.openremote.app.models
+
+data class ORAppConfig(
+ val id: Int,
+ val realm: String,
+ val initialUrl: String,
+ val url: String,
+ val menuEnabled: Boolean = false,
+ val menuPosition: String = "BOTTOM_LEFT",
+ val menuImage: String?,
+ val primaryColor: String?,
+ val secondaryColor: String?,
+ val links: List<ORLinkConfig>?
+)
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORLinkConfig.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORLinkConfig.kt
new file mode 100644
index 000000000..cd04985b7
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/models/ORLinkConfig.kt
@@ -0,0 +1,6 @@
+package io.openremote.app.models
+
+data class ORLinkConfig(
+ val displayText: String,
+ val pageLink: String
+)
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/network/ApiManager.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/network/ApiManager.kt
new file mode 100644
index 000000000..f6831bdb5
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/network/ApiManager.kt
@@ -0,0 +1,145 @@
+package io.openremote.app.network
+
+import android.net.Uri
+import android.util.Log
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import io.openremote.app.models.ORAppConfig
+import java.net.HttpURLConnection
+import java.net.URL
+import java.util.concurrent.Executors
+
+
+typealias ResponseBlock<T> = (statusCode: Int, model: T?, error: Throwable?) -> Unit
+
+class ApiManager(private val baseUrl: String) {
+
+ companion object {
+ var accessToken: String? = null
+ }
+
+ enum class HttpMethod {
+ GET,
+ POST,
+ PUT,
+ }
+
+ fun getAppConfig(callback: ResponseBlock<ORAppConfig>?) {
+ get(arrayOf("app", "config"), callback)
+ }
+
+ /*********************************Private functions*******************************/
+ private fun createUrlRequest(
+ method: HttpMethod,
+ pathComponents: Array<String>,
+ queryParameters: Map<String, Any>? = null
+ ): HttpURLConnection {
+ val builder = Uri.parse(baseUrl).buildUpon()
+
+ for (pathComponent in pathComponents) builder.appendPath(pathComponent)
+
+ if (queryParameters != null) {
+ for ((queryParameterKey, queryParameterValue) in queryParameters)
+ builder.appendQueryParameter(
+ queryParameterKey,
+ queryParameterValue.toString()
+ )
+ }
+
+ return URL(builder.build().toString())
+ .openConnection()
+ .let {
+ it as HttpURLConnection
+ }.apply {
+ requestMethod = method.toString()
+ setRequestProperty("Accept", "application/json")
+
+ if (method == HttpMethod.POST || method == HttpMethod.PUT) {
+ setRequestProperty("Content-Type", "application/json")
+ doOutput = true
+ }
+ }
+ }
+
+ private inline fun <reified T : Any> get(
+ pathComponents: Array<String>,
+ noinline callback: ResponseBlock<T>?,
+ queryParameters: Map<String, Any>? = null
+ ) {
+ Executors.newCachedThreadPool().execute {
+ val urlRequest = createUrlRequest(HttpMethod.GET, pathComponents, queryParameters)
+ parseResponse<T>(urlRequest, callback)
+ }
+ }
+
+
+ private inline fun <reified T : Any> post(
+ pathComponents: Array<String>, item: Any, noinline callback: ResponseBlock<T>?
+ ) {
+ Executors.newCachedThreadPool().execute {
+
+ val urlRequest = createUrlRequest(HttpMethod.POST, pathComponents)
+ urlRequest.apply {
+ writeBody(item)
+ }.let { httpConnection ->
+ parseResponse(httpConnection, callback)
+ }
+ }
+ }
+
+ private inline fun <reified T : Any> put(
+ pathComponents: Array<String>, item: Any, noinline callback: ResponseBlock<T>?
+ ) {
+ Executors.newCachedThreadPool().execute {
+
+ val urlRequest = createUrlRequest(HttpMethod.PUT, pathComponents)
+ urlRequest.apply {
+ writeBody(item)
+ }.let { httpConnection ->
+ parseResponse(httpConnection, callback)
+ }
+ }
+ }
+
+ private inline fun <reified T : Any> parseResponse(
+ httpConnection: HttpURLConnection,
+ noinline callback: ResponseBlock<T>?
+ ) {
+ val model = if (httpConnection.responseCode == 200) {
+ try {
+ jacksonObjectMapper().readValue(
+ httpConnection.inputStream.bufferedReader().readText(),
+ T::class.java
+ )
+ } catch (e: Exception) {
+ Log.e(this::class.simpleName, e.message, e)
+ null
+ }
+ } else {
+ null
+ }
+ val error = try {
+
+ if (httpConnection.responseCode !in 200..299) {
+ val errorResponse = httpConnection.errorStream.bufferedReader().readText()
+ Throwable(errorResponse)
+ } else {
+ null
+ }
+ } catch (e: Exception) {
+ e
+ }
+ error?.let {
+ Log.e(this::class.simpleName, it.message, it)
+ }
+ callback?.invoke(httpConnection.responseCode, model, error)
+ httpConnection.disconnect()
+ }
+
+ private fun HttpURLConnection.writeBody(item: Any) {
+ val outputWriter = outputStream.bufferedWriter()
+ outputWriter.write(
+ jacksonObjectMapper().writeValueAsString(item)
+ )
+ outputWriter.flush()
+ }
+}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceBootCompleteReceiver.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceBootCompleteReceiver.kt
similarity index 93%
rename from console/android/src/main/java/org/openremote/android/service/GeofenceBootCompleteReceiver.kt
rename to console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceBootCompleteReceiver.kt
index e72fdbcfb..e80c4164b 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceBootCompleteReceiver.kt
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceBootCompleteReceiver.kt
@@ -18,11 +18,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.android.service
+package io.openremote.app.service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
+import io.openremote.app.service.GeofenceProvider
class GeofenceBootCompleteReceiver : BroadcastReceiver() {
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceProvider.kt
similarity index 87%
rename from console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
rename to console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceProvider.kt
index e89b38600..e2b462419 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceProvider.kt
@@ -1,6 +1,6 @@
-package org.openremote.android.service
+package io.openremote.app.service
-import android.Manifest.permission.ACCESS_FINE_LOCATION
+import android.Manifest.permission.*
import android.annotation.SuppressLint
import android.app.Activity
import android.app.PendingIntent
@@ -11,8 +11,8 @@ import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.android.gms.location.*
-import org.openremote.android.MainActivity
-import org.openremote.android.R
+import io.openremote.app.ui.MainActivity
+import io.openremote.app.R
import java.net.URL
import java.util.*
import java.util.logging.Level
@@ -188,7 +188,22 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
.remove(geofenceDisabledKey)
.apply()
- if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && !sharedPreferences.getBoolean(locationPermissionAskedKey, false)) {
+ val hasPermission = when(android.os.Build.VERSION.SDK_INT) {
+ android.os.Build.VERSION_CODES.Q -> {
+ ContextCompat.checkSelfPermission(
+ context,
+ ACCESS_BACKGROUND_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ } else -> {
+ ContextCompat.checkSelfPermission(
+ context,
+ ACCESS_FINE_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ }
+ }
+
+ if (!hasPermission && !sharedPreferences.getBoolean(
+ locationPermissionAskedKey, false)) {
sharedPreferences.edit().putBoolean(locationPermissionAskedKey, true).apply()
enableCallback = callback
registerPermissions(activity)
@@ -213,6 +228,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
//context.stopService(Intent(context, LocationService::class.java))
}
+ @SuppressLint("MissingPermission")
fun getLocation(activity: Activity, callback: GeofenceCallback?) {
locationCallback = callback
@@ -251,7 +267,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
// Remove previous fences that no longer exist
val oldFences = getGeofences(context)
- val remainingFences: ArrayList<GeofenceProvider.GeofenceDefinition> = arrayListOf()
+ val remainingFences: ArrayList<GeofenceDefinition> = arrayListOf()
oldFences.forEach { oldFence ->
if (geofences.none { Objects.equals(it.id, oldFence.id) }) {
@@ -283,7 +299,19 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
Thread {
- val hasPermission = ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
+ val hasPermission = when(android.os.Build.VERSION.SDK_INT) {
+ android.os.Build.VERSION_CODES.Q -> {
+ ContextCompat.checkSelfPermission(
+ context,
+ ACCESS_BACKGROUND_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ } else -> {
+ ContextCompat.checkSelfPermission(
+ context,
+ ACCESS_FINE_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ }
+ }
callback?.accept(hashMapOf(
"action" to "PROVIDER_ENABLE",
@@ -309,8 +337,11 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
private fun registerPermissions(activity: Activity) {
LOG.info("Requesting geofence permissions")
- val permissions = arrayOf(ACCESS_FINE_LOCATION)
- ActivityCompat.requestPermissions(activity, permissions, locationReponseCode)
+ val permissions = mutableListOf(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION)
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
+ permissions.add(ACCESS_BACKGROUND_LOCATION)
+ }
+ ActivityCompat.requestPermissions(activity, permissions.toTypedArray(), locationReponseCode)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceTransitionsIntentService.kt
similarity index 99%
rename from console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
rename to console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceTransitionsIntentService.kt
index ba65c241c..1ed438139 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/GeofenceTransitionsIntentService.kt
@@ -1,4 +1,4 @@
-package org.openremote.android.service
+package io.openremote.app.service
import android.content.BroadcastReceiver
import android.content.Context
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/service/NotificationResource.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/NotificationResource.kt
new file mode 100644
index 000000000..3fdf1d735
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/NotificationResource.kt
@@ -0,0 +1,98 @@
+package io.openremote.app.service
+
+import android.content.Context
+import android.content.SharedPreferences
+import androidx.preference.PreferenceManager
+import java.net.HttpURLConnection
+import java.net.URL
+import java.util.concurrent.Executors
+import java.util.logging.Logger
+
+class NotificationResource(context: Context) {
+ private val sharedPreferences: SharedPreferences =
+ PreferenceManager.getDefaultSharedPreferences(context)
+
+ fun executeRequest(httpMethod: String, appUrl: String, data: String) {
+ val project = sharedPreferences.getString("project", null)
+ val realm = sharedPreferences.getString("realm", null)
+
+ if (!project.isNullOrBlank() && !realm.isNullOrBlank()) {
+ Executors.newCachedThreadPool().execute {
+ URL(appUrl)
+ .openConnection()
+ .let {
+ it as HttpURLConnection
+ }.apply {
+ requestMethod = httpMethod
+ setRequestProperty("Accept", "application/json")
+
+
+ setRequestProperty("Content-Type", "application/json")
+ doOutput = true
+
+ val outputWriter = outputStream.bufferedWriter()
+ outputWriter.write(data)
+ outputWriter.flush()
+ }
+ }
+ }
+ }
+
+ fun notificationDelivered(notificationId: Long, fcmToken: String?) {
+ LOG.info("Notification status update 'delivered': $notificationId")
+
+ val project = sharedPreferences.getString("project", null)
+ val realm = sharedPreferences.getString("realm", null)
+
+ if (!project.isNullOrBlank() && !realm.isNullOrBlank()) {
+ Executors.newCachedThreadPool().execute {
+ URL("https://${project}.openremote.io/api/$realm/notification/${notificationId}/delivered?targetId=$fcmToken")
+ .openConnection()
+ .let {
+ it as HttpURLConnection
+ }.apply {
+ requestMethod = "PUT"
+ setRequestProperty("Accept", "application/json")
+
+
+ setRequestProperty("Content-Type", "application/json")
+ doOutput = true
+ }
+ }
+ }
+ }
+
+ fun notificationAcknowledged(notificationId: Long, fcmToken: String?, acknowledgement: String) {
+ val project = sharedPreferences.getString("project", null)
+ val realm = sharedPreferences.getString("realm", null)
+
+ if (!project.isNullOrBlank() && !realm.isNullOrBlank()) {
+ Executors.newCachedThreadPool().execute {
+ URL("https://${project}.openremote.io/api/$realm/notification/${notificationId}/acknowledged?targetId=$fcmToken")
+ .openConnection()
+ .let {
+ it as HttpURLConnection
+ }.apply {
+ requestMethod = "PUT"
+ setRequestProperty("Accept", "application/json")
+
+
+ setRequestProperty("Content-Type", "application/json")
+ doOutput = true
+
+ val outputWriter = outputStream.bufferedWriter()
+ outputWriter.write(
+ "{\"acknowledgement\": \"$acknowledgement\"}"
+ )
+ outputWriter.flush()
+ }
+ }
+ }
+ }
+
+ companion object {
+ private val LOG = Logger.getLogger(
+ NotificationResource::class.java.name
+ )
+ }
+}
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/service/ORFirebaseMessagingService.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/ORFirebaseMessagingService.kt
new file mode 100644
index 000000000..5d3be29ee
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/ORFirebaseMessagingService.kt
@@ -0,0 +1,226 @@
+package io.openremote.app.service
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.media.RingtoneManager
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.core.app.NotificationCompat
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.firebase.messaging.RemoteMessage
+import io.openremote.app.BuildConfig.APPLICATION_ID
+import io.openremote.app.ui.MainActivity
+import io.openremote.app.R
+import io.openremote.app.models.ORAlertAction
+import io.openremote.app.models.ORAlertButton
+import java.util.*
+import java.util.logging.Level
+import java.util.logging.Logger
+
+class ORFirebaseMessagingService : com.google.firebase.messaging.FirebaseMessagingService() {
+
+ private var notificationResource: NotificationResource? = null
+
+ class MyBroadcastReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ LOG.info("TODO: Remove notification")
+ }
+ }
+
+ override fun onCreate() {
+ super.onCreate()
+ notificationResource = NotificationResource(applicationContext)
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ createNotificationChannel()
+ }
+ }
+
+ /**
+ * Called when message is received.
+ *
+ * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
+ */
+ // [START receive_message]
+ override fun onMessageReceived(remoteMessage: RemoteMessage) {
+ // [START_EXCLUDE]
+ // There are two types of messages data messages and notification messages. Data messages are handled
+ // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
+ // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
+ // is in the foreground. When the app is in the background an automatically generated notification is displayed.
+ // When the user taps on the notification they are returned to the app. Messages containing both notification
+ // and data payloads are treated as notification messages. The Firebase console always sends notification
+ // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
+ // [END_EXCLUDE]
+
+ // TODO(developer): Handle FCM messages here.
+ // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
+ LOG.fine("Received message from: " + remoteMessage.from)
+
+ // If the message contains a notification then we assume it has been shown to the user
+ if (remoteMessage.notification != null) {
+ LOG.fine(
+ "Message contains notification body: " + remoteMessage.notification!!.getBody()
+ )
+ } else if (remoteMessage.data.isNotEmpty()) {
+ val messageData: Map<String, String> = remoteMessage.data
+
+ // Mark as delivered on the server
+ val notificationIdStr = messageData["notification-id"]
+ var notificationId: Long? = null
+ if (notificationIdStr != null && notificationIdStr.isNotEmpty()) {
+ notificationId = notificationIdStr.toLong()
+ val consoleId: String? = getSharedPreferences(
+ applicationContext.getString(R.string.OR_CONSOLE_NAME),
+ Context.MODE_PRIVATE
+ ).getString("consoleId", "")
+ if (!consoleId.isNullOrBlank()) {
+ notificationResource?.notificationDelivered(notificationId, consoleId)
+ }
+ }
+ val isSilent = !messageData.containsKey("or-title")
+ if (isSilent) {
+ when (val action: String? = remoteMessage.data.get("action")) {
+ "GEOFENCE_REFRESH" -> {
+ val geofenceProvider = GeofenceProvider(applicationContext)
+ geofenceProvider.refreshGeofences()
+ }
+ else -> {
+ val broadCastIntent = Intent(MainActivity.ACTION_BROADCAST)
+ broadCastIntent.putExtra("action", action)
+ sendBroadcast(broadCastIntent)
+ }
+ }
+ } else {
+ val title = messageData["or-title"]
+ val body = messageData["or-body"]
+ var buttonORS: Array<ORAlertButton>? = null
+ var actionOR: ORAlertAction? = null
+
+ // Check for action (to be executed when notification is clicked)
+ if (messageData.containsKey("action")) {
+ val actionJson = messageData["action"]
+ if (actionJson != null && !actionJson.isEmpty()) {
+ try {
+ actionOR = ObjectMapper().readValue(
+ actionJson,
+ ORAlertAction::class.java
+ )
+ } catch (e: Exception) {
+ LOG.log(Level.SEVERE, "Failed to de-serialise alert action", e)
+ }
+ }
+ }
+
+ // Check for buttons
+ if (messageData.containsKey("buttons")) {
+ val buttonsJson = messageData["buttons"]
+ if (buttonsJson != null && buttonsJson.isNotEmpty()) {
+ try {
+ buttonORS = ObjectMapper().readValue(
+ buttonsJson,
+ Array<ORAlertButton>::class.java
+ )
+ } catch (e: Exception) {
+ LOG.log(Level.SEVERE, "Failed to de-serialise alert actions", e)
+ }
+ }
+ }
+ handleNotification(notificationId, title, body, actionOR, buttonORS)
+ }
+ }
+ }
+
+ override fun onNewToken(token: String) {
+ super.onNewToken(token)
+ }
+
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun createNotificationChannel() {
+ val channelName = "OR Eindhoven Message Service"
+ val channel = NotificationChannel(
+ getString(R.string.NOTIFICATION_CHANNEL_ID),
+ channelName, NotificationManager.IMPORTANCE_HIGH
+ )
+ channel.setShowBadge(false)
+ val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ service.createNotificationChannel(channel)
+ }
+
+ private fun handleNotification(
+ notificationId: Long?,
+ title: String?,
+ body: String?,
+ actionOR: ORAlertAction?,
+ buttonORS: Array<ORAlertButton>?
+ ) {
+ val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
+ val notificationBuilder = NotificationCompat.Builder(this, getString(R.string.NOTIFICATION_CHANNEL_ID))
+ .setContentTitle(title)
+ .setWhen(Date().time)
+ .setShowWhen(true)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(body))
+ .setContentText(body)
+ .setSmallIcon(R.drawable.notification_icon)
+ .setWhen(0)
+ .setPriority(Notification.PRIORITY_MAX)
+ .setSound(defaultSoundUri)
+ .setDeleteIntent(createActionIntent(notificationId, "\"CLOSED\"", null))
+ if (actionOR != null) {
+ notificationBuilder.setContentIntent(createActionIntent(notificationId, null, actionOR))
+ }
+ if (buttonORS != null) {
+ for (alertButton in buttonORS) {
+ notificationBuilder.addAction(
+ NotificationCompat.Action(
+ R.drawable.empty,
+ alertButton.title,
+ createActionIntent(
+ notificationId,
+ alertButton.title,
+ alertButton.action
+ )
+ )
+ )
+ }
+ }
+ LOG.fine(
+ "Showing notification id=$notificationId, title=$title, body=$body, action=$actionOR, buttons=" + (buttonORS?.size
+ ?: 0)
+ )
+ val notificationManager =
+ getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
+ notificationManager?.notify(notificationId.hashCode(), notificationBuilder.build())
+ }
+
+ private fun createActionIntent(
+ notificationId: Long?,
+ acknowledgement: String?,
+ ORAlertAction: ORAlertAction?
+ ): PendingIntent {
+ val actionIntent = Intent(this, ORMessagingActionService::class.java)
+ actionIntent.putExtra("notificationId", notificationId)
+ actionIntent.putExtra("acknowledgement", acknowledgement)
+ actionIntent.action = System.currentTimeMillis().toString()
+ if (ORAlertAction?.url != null && !ORAlertAction.url.isNullOrEmpty()
+ ) {
+ actionIntent.putExtra("appUrl", ORAlertAction.url)
+ actionIntent.putExtra("httpMethod", ORAlertAction.httpMethod)
+ actionIntent.putExtra("silent", ORAlertAction.isSilent)
+ actionIntent.putExtra("openInBrowser", ORAlertAction.isOpenInBrowser)
+ actionIntent.putExtra("data", ObjectMapper().writeValueAsString(ORAlertAction.data))
+ }
+ return PendingIntent.getService(this, 0, actionIntent, PendingIntent.FLAG_ONE_SHOT)
+ }
+
+ companion object {
+ private val LOG = Logger.getLogger(
+ ORFirebaseMessagingService::class.java.name
+ )
+ }
+}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/ORMessagingActionService.java
similarity index 86%
rename from console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
rename to console/android/GenericApp/app/src/main/java/io/openremote/app/service/ORMessagingActionService.java
index 7eb865120..1a046ab5b 100644
--- a/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/service/ORMessagingActionService.java
@@ -1,4 +1,4 @@
-package org.openremote.android;
+package io.openremote.app.service;
import android.app.IntentService;
import android.app.NotificationManager;
@@ -6,14 +6,16 @@ import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
-import androidx.annotation.Nullable;
import android.text.TextUtils;
-import org.openremote.android.service.TokenService;
+import androidx.annotation.Nullable;
+
+import io.openremote.app.R;
+
public class ORMessagingActionService extends IntentService {
- private TokenService tokenService;
+ private NotificationResource notificationResource;
public ORMessagingActionService() {
super("org.openremote.android.ORMessagingActionService");
@@ -22,7 +24,7 @@ public class ORMessagingActionService extends IntentService {
@Override
public void onCreate() {
super.onCreate();
- tokenService = new TokenService(getApplicationContext());
+ notificationResource = new NotificationResource(getApplicationContext());
}
@Override
@@ -40,7 +42,7 @@ public class ORMessagingActionService extends IntentService {
String consoleId = getSharedPreferences(getApplicationContext().getString(R.string.OR_CONSOLE_NAME), Context.MODE_PRIVATE).getString("consoleId", "");
if (!TextUtils.isEmpty(consoleId)) {
- tokenService.notificationAcknowledged(notificationId, consoleId, acknowledgement);
+ notificationResource.notificationAcknowledged(notificationId, consoleId, acknowledgement);
}
String appUrl = intent.getStringExtra("appUrl");
@@ -60,7 +62,7 @@ public class ORMessagingActionService extends IntentService {
startActivity(i);
} else if (silent) {
// Do silent HTTP request
- tokenService.executeRequest(httpMethod, appUrl, data);
+ notificationResource.executeRequest(httpMethod, appUrl, data);
} else {
Intent activityIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage(getApplicationContext().getPackageName());
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/MainActivity.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/MainActivity.kt
new file mode 100644
index 000000000..7c24f64d1
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/MainActivity.kt
@@ -0,0 +1,741 @@
+package io.openremote.app.ui
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.annotation.TargetApi
+import android.app.Activity
+import android.app.DownloadManager
+import android.content.*
+import android.content.pm.ApplicationInfo
+import android.content.pm.PackageManager
+import android.content.res.ColorStateList
+import android.graphics.Bitmap
+import android.graphics.Color
+import android.net.ConnectivityManager
+import android.net.Uri
+import android.os.*
+import android.text.TextUtils
+import android.view.KeyEvent
+import android.view.View
+import android.view.ViewGroup
+import android.webkit.*
+import android.webkit.ConsoleMessage.MessageLevel
+import android.webkit.WebView.WebViewTransport
+import android.widget.ProgressBar
+import android.widget.RelativeLayout
+import android.widget.Toast
+import androidx.appcompat.widget.PopupMenu
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
+import androidx.preference.PreferenceManager
+import com.fasterxml.jackson.core.JsonProcessingException
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import com.google.android.material.floatingactionbutton.FloatingActionButton
+import com.google.firebase.iid.FirebaseInstanceId
+import io.openremote.app.R
+import io.openremote.app.models.ORAppConfig
+import io.openremote.app.service.GeofenceProvider
+import kotlinx.android.synthetic.main.activity_main.*
+import org.json.JSONException
+import org.json.JSONObject
+import java.util.*
+import java.util.logging.Level
+import java.util.logging.Logger
+
+class MainActivity : Activity() {
+ private val connectivityChangeReceiver: ConnectivityChangeReceiver =
+ ConnectivityChangeReceiver()
+ private var timeOutHandler: Handler? = null
+ private var timeOutRunnable: Runnable? = null
+ private var progressBar: ProgressBar? = null
+ private var webViewTimeout = WEBVIEW_LOAD_TIMEOUT_DEFAULT
+ private var webViewLoaded = false
+ private var sharedPreferences: SharedPreferences? = null
+ private var geofenceProvider: GeofenceProvider? = null
+ private var consoleId: String? = null
+ private var appConfig: ORAppConfig? = null
+ private var onDownloadCompleteReciever: BroadcastReceiver = object : BroadcastReceiver() {
+ override fun onReceive(ctxt: Context, intent: Intent) {
+ val action = intent.action
+ if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == action) {
+ Toast.makeText(applicationContext, R.string.download_completed, Toast.LENGTH_LONG)
+ .show()
+ }
+ }
+ }
+
+ private val clientUrl: String?
+ get() {
+ var returnValue: String? = null
+
+ sharedPreferences?.let { pref ->
+ pref.getString("project", null)?.let { projectName ->
+ pref.getString("realm", null)?.let { realmName ->
+ returnValue = "https://${projectName}.openremote.io/api/$realmName"
+ }
+ }
+ }
+
+ return returnValue
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
+
+ try {
+ val timeoutStr = getString(R.string.OR_CONSOLE_LOAD_TIMEOUT)
+ webViewTimeout = timeoutStr.toInt()
+ } catch (nfe: NumberFormatException) {
+ println("Could not parse console load timeout value: $nfe")
+ }
+
+ // Enable remote debugging of WebView from Chrome Debugger tools
+ if (0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) {
+ LOG.info("Enabling remote debugging")
+ WebView.setWebContentsDebuggingEnabled(true)
+ }
+ setContentView(R.layout.activity_main)
+ if (savedInstanceState != null) {
+ webView?.restoreState(savedInstanceState)
+ } else {
+ initializeWebView()
+ }
+
+ openIntentUrl(intent)
+ progressBar = findViewById(R.id.webProgressBar)
+ progressBar?.max = 100
+ progressBar?.progress = 1
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ openIntentUrl(intent)
+ }
+
+ private fun openIntentUrl(intent: Intent) {
+ if (intent.hasExtra(APP_CONFIG_KEY)) {
+ appConfig = jacksonObjectMapper().readValue(
+ intent.getStringExtra(APP_CONFIG_KEY),
+ ORAppConfig::class.java
+ )
+ }
+ if (appConfig != null) {
+
+ if (appConfig!!.menuEnabled && !appConfig!!.links.isNullOrEmpty()) {
+ val floatingActionButton = FloatingActionButton(this)
+
+ val layoutParams = RelativeLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+
+ val margin = 36
+ when (appConfig!!.menuPosition) {
+ "BOTTOM_RIGHT" -> {
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_END)
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
+ layoutParams.marginEnd = margin
+ layoutParams.bottomMargin = margin
+ }
+ "TOP_RIGHT" -> {
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_END)
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
+ layoutParams.marginEnd = margin
+ layoutParams.topMargin = margin
+ }
+ "TOP_LEFT" -> {
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START)
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
+ layoutParams.marginStart = margin
+ layoutParams.topMargin = margin
+ }
+ else -> {
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START)
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
+ layoutParams.marginStart = margin
+ layoutParams.bottomMargin = margin
+ }
+ }
+ floatingActionButton.layoutParams = layoutParams
+ floatingActionButton.setImageResource(R.drawable.ic_menu)
+ if(!appConfig!!.primaryColor.isNullOrBlank()) {
+ floatingActionButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor(appConfig!!.primaryColor!!))
+ }
+ floatingActionButton.setOnClickListener {
+ // We are showing only toast message. However, you can do anything you need.
+ val popupMenu = PopupMenu(this@MainActivity, it)
+ for ((index, link) in appConfig!!.links!!.withIndex()) {
+ popupMenu.menu.add(index, index, index, link.displayText)
+ }
+ popupMenu.setOnMenuItemClickListener { item ->
+ loadUrl(appConfig!!.links!![item.itemId].pageLink)
+ true
+ }
+ popupMenu.show()
+ }
+
+ activity_web.addView(floatingActionButton)
+ }
+ LOG.fine("Loading web view: ${appConfig!!.initialUrl}")
+ loadUrl(appConfig!!.initialUrl)
+ } else if (!intent.hasExtra("appUrl")) {
+ val url = clientUrl
+ LOG.fine("Loading web view: $url")
+ loadUrl(url)
+ } else {
+ var url = clientUrl
+ val intentUrl = intent.getStringExtra("appUrl")
+ if (intentUrl != null) {
+ url = if (intentUrl.startsWith("http") || intentUrl.startsWith("https")) {
+ intentUrl
+ } else {
+ url + intentUrl
+ }
+ }
+ LOG.fine("Loading web view: $url")
+ loadUrl(url)
+ }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ registerReceiver(
+ connectivityChangeReceiver,
+ IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
+ )
+ registerReceiver(
+ onDownloadCompleteReciever,
+ IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
+ )
+ }
+
+ override fun onPause() {
+ super.onPause()
+ unregisterReceiver(connectivityChangeReceiver)
+ unregisterReceiver(onDownloadCompleteReciever)
+ }
+
+ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
+ if (webView != null) {
+ if (event.action == KeyEvent.ACTION_DOWN) {
+ when (keyCode) {
+ KeyEvent.KEYCODE_BACK -> {
+ if (webView.canGoBack()) {
+ webView.goBack()
+ } else {
+ finish()
+ }
+ return true
+ }
+ }
+ }
+ }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ webView.saveState(outState)
+ }
+
+ private fun reloadWebView() {
+ var url = webView.url
+ if ("about:blank" == url) {
+ url = clientUrl
+ LOG.fine("Reloading web view: $url")
+ loadUrl(url)
+ }
+ }
+
+ @SuppressLint("SetJavaScriptEnabled")
+ fun initializeWebView() {
+ LOG.fine("Initializing web view")
+ val webAppInterface = WebAppInterface(this)
+ webView.addJavascriptInterface(webAppInterface, "MobileInterface")
+ val webSettings = webView.settings
+ webSettings.javaScriptEnabled = true
+ webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
+ webSettings.cacheMode = WebSettings.LOAD_DEFAULT
+ webSettings.domStorageEnabled = true
+ webSettings.databaseEnabled = true
+ webSettings.setSupportMultipleWindows(true)
+ webView.setOnLongClickListener { true }
+ webView.isLongClickable = false
+ webView.webViewClient = object : WebViewClient() {
+ override fun onReceivedHttpError(
+ view: WebView,
+ request: WebResourceRequest,
+ errorResponse: WebResourceResponse
+ ) {
+ // When initialising Keycloak with an invalid offline refresh token (e.g. wrong nonce because
+ // server was reinstalled), we detect the failure and then don't show an error view. We clear the stored
+ // invalid token. The web app will then start a new login.
+ if (request.url.lastPathSegment != null && request.url.lastPathSegment == "token" && request.method == "POST" && errorResponse.statusCode == 400) {
+ storeData(getString(R.string.SHARED_PREF_REFRESH_TOKEN), null)
+ return
+ }
+ handleError(
+ errorResponse.statusCode,
+ errorResponse.reasonPhrase,
+ request.url.toString(),
+ request.isForMainFrame
+ )
+ }
+
+ override fun onReceivedError(
+ view: WebView,
+ errorCode: Int,
+ description: String,
+ failingUrl: String
+ ) {
+ handleError(errorCode, description, failingUrl, true)
+ }
+
+ @TargetApi(Build.VERSION_CODES.M)
+ override fun onReceivedError(
+ view: WebView,
+ request: WebResourceRequest,
+ error: WebResourceError
+ ) {
+
+ // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
+ if ("net::ERR_CACHE_MISS".contentEquals(error.description)) {
+ return
+ }
+ if (request.url.toString() == "about:blank" && error.errorCode == ERROR_UNSUPPORTED_SCHEME) {
+ return
+ }
+ handleError(
+ error.errorCode, error.description.toString(),
+ request.url.toString(), request.isForMainFrame
+ )
+ }
+
+ override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
+ progressBar!!.visibility = View.VISIBLE
+ timeOutRunnable = Runnable {
+ if (!webViewLoaded) {
+ handleError(ERROR_TIMEOUT, "Connection timed out", url, true)
+ }
+ }
+ timeOutHandler = Handler(Looper.myLooper())
+ timeOutHandler!!.postDelayed(timeOutRunnable, 5000)
+ }
+
+ override fun onPageFinished(view: WebView, url: String) {
+ webViewLoaded = true
+ progressBar!!.visibility = View.GONE
+ timeOutHandler!!.removeCallbacks(timeOutRunnable)
+ }
+
+ override fun shouldOverrideUrlLoading(
+ view: WebView,
+ request: WebResourceRequest
+ ): Boolean {
+ if (request.url.scheme.equals("webbrowser", ignoreCase = true)) {
+ val newUrl = request.url.buildUpon().scheme("https").build().toString()
+ val i = Intent(Intent.ACTION_VIEW)
+ i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ i.data = Uri.parse(newUrl)
+ startActivity(i)
+ return true
+ }
+ return super.shouldOverrideUrlLoading(view, request)
+ }
+
+ private fun handleError(
+ errorCode: Int,
+ description: String,
+ failingUrl: String?,
+ isForMainFrame: Boolean
+ ) {
+ LOG.warning("Error requesting '$failingUrl': $errorCode($description)")
+
+ // This will be the URL loaded into the webview itself (false for images etc. of the main page)
+ if (isForMainFrame) {
+
+ // Check page load error URL
+ val errorUrl = getString(R.string.OR_CONSOLE_LOAD_ERROR_URL)
+ if (!TextUtils.isEmpty(errorUrl) && failingUrl != errorUrl) {
+ LOG.info("Loading error URL: $errorUrl")
+ loadUrl(errorUrl)
+ return
+ }
+ } else {
+ if (java.lang.Boolean.parseBoolean(getString(R.string.OR_CONSOLE_IGNORE_PAGE_ERRORS))) {
+ return
+ }
+
+ //TODO should we always ignore image errors?
+ if (failingUrl != null && (failingUrl.endsWith("png")
+ || failingUrl.endsWith("jpg")
+ || failingUrl.endsWith("ico"))
+ ) {
+ LOG.info("Ignoring error loading image resource")
+ return
+ }
+ }
+ }
+ }
+ webView.webChromeClient = object : WebChromeClient() {
+ override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
+ val msg =
+ "WebApp console (" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + "): " + consoleMessage.message()
+ when (consoleMessage.messageLevel()) {
+ MessageLevel.DEBUG, MessageLevel.TIP -> LOG.fine(msg)
+ MessageLevel.LOG -> LOG.info(msg)
+ else -> LOG.severe(msg)
+ }
+ return true
+ }
+
+ override fun onProgressChanged(view: WebView, progress: Int) {
+ progressBar!!.progress = progress
+ }
+
+ override fun onCreateWindow(
+ view: WebView,
+ dialog: Boolean,
+ userGesture: Boolean,
+ resultMsg: Message
+ ): Boolean {
+ val newWebView = WebView(this@MainActivity)
+ view.addView(newWebView)
+ val transport = resultMsg.obj as WebViewTransport
+ transport.webView = newWebView
+ resultMsg.sendToTarget()
+ newWebView.webViewClient = object : WebViewClient() {
+ override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
+ val browserIntent = Intent(Intent.ACTION_VIEW)
+ browserIntent.data = Uri.parse(url)
+ startActivity(browserIntent)
+ return true
+ }
+ }
+ return true
+ }
+ }
+
+ webView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
+ val writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE
+ if (ContextCompat.checkSelfPermission(
+ this@MainActivity,
+ writePermission
+ ) != PackageManager.PERMISSION_GRANTED
+ ) {
+ // Write permission has not been granted yet, request it.
+ ActivityCompat.requestPermissions(
+ this@MainActivity,
+ arrayOf(writePermission),
+ WRITE_PERMISSION_FOR_DOWNLOAD
+ )
+ } else {
+ val request = DownloadManager.Request(Uri.parse(url))
+ request.setMimeType(mimetype)
+ //------------------------COOKIE!!------------------------
+ val cookies = CookieManager.getInstance().getCookie(url)
+ request.addRequestHeader("cookie", cookies)
+ //------------------------COOKIE!!------------------------
+ request.addRequestHeader("User-Agent", userAgent)
+ request.setDescription("Downloading file...")
+ request.setTitle(
+ URLUtil.guessFileName(
+ url,
+ contentDisposition,
+ mimetype
+ )
+ )
+ request.allowScanningByMediaScanner()
+ request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
+ request.setDestinationInExternalPublicDir(
+ Environment.DIRECTORY_DOWNLOADS,
+ URLUtil.guessFileName(url, contentDisposition, mimetype)
+ )
+ val dm =
+ getSystemService(DOWNLOAD_SERVICE) as DownloadManager
+ Toast.makeText(applicationContext, R.string.downloading_file, Toast.LENGTH_LONG)
+ .show()
+ dm.enqueue(request)
+ }
+ }
+ }
+
+ private fun loadUrl(url: String?) {
+ webViewLoaded = false
+ val temp = url!!.replace(" ", "%20")
+ webView.loadUrl(temp)
+ }
+
+ override fun onRequestPermissionsResult(
+ requestCode: Int,
+ permissions: Array<String>,
+ grantResults: IntArray
+ ) {
+ if (requestCode == WRITE_PERMISSION_FOR_DOWNLOAD) {
+ if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ Toast.makeText(applicationContext, R.string.downloading_file, Toast.LENGTH_LONG)
+ .show()
+ }
+ } else if (requestCode == GeofenceProvider.locationReponseCode) {
+ geofenceProvider?.onRequestPermissionsResult(requestCode, permissions, grantResults)
+ } else {
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+ }
+ }
+
+ private inner class WebAppInterface(
+ private val activity: Activity
+ ) {
+ @JavascriptInterface
+ @Throws(JSONException::class)
+ public fun postMessage(jsonMessage: String) {
+ val reader = JSONObject(jsonMessage)
+ val messageType = reader.getString("type")
+ val data = reader.optJSONObject("data")
+ LOG.info("Received WebApp message: $data")
+
+ when (messageType) {
+ "error" -> {
+ LOG.fine("Received WebApp message, error: " + data?.getString("error"))
+ val mainHandler = Handler(mainLooper)
+ Toast.makeText(
+ this@MainActivity,
+ "Error occurred ${data?.getString("error")}",
+ Toast.LENGTH_LONG
+ ).show()
+ }
+ "provider" -> {
+ data?.let {
+ val action = it.getString("action")
+ if (!action.isNullOrEmpty()) {
+ val provider = it.getString("provider")
+ when {
+ provider.equals("geofence", ignoreCase = true) -> {
+ handleGeofenceProviderMessage(it)
+ }
+ provider.equals("push", ignoreCase = true) -> {
+ handlePushProviderMessage(it)
+ }
+ provider.equals("storage", ignoreCase = true) -> {
+ handleStorageProviderMessage(it)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ @Throws(JSONException::class)
+ private fun handleGeofenceProviderMessage(data: JSONObject) {
+ val action = data.getString("action")
+ if (geofenceProvider == null) {
+ geofenceProvider = GeofenceProvider(activity)
+ }
+ when {
+ action.equals("PROVIDER_INIT", ignoreCase = true) -> {
+ val initData: Map<String, Any> = geofenceProvider!!.initialize()
+ notifyClient(initData)
+ }
+ action.equals("PROVIDER_ENABLE", ignoreCase = true) -> {
+ val consoleId = data.getString("consoleId")
+ (activity as MainActivity).consoleId = consoleId
+ val baseUrl = sharedPreferences?.let { pref ->
+ pref.getString("project", null)?.let { projectName ->
+ pref.getString("realm", null)?.let { realmName ->
+ "https://${projectName}.openremote.io/api/$realmName"
+ }
+ }
+ } ?: ""
+ geofenceProvider?.enable(this@MainActivity, baseUrl,
+ consoleId, object : GeofenceProvider.GeofenceCallback {
+ override fun accept(responseData: Map<String, Any>) {
+ notifyClient(responseData)
+ }
+ })
+ }
+ action.equals("PROVIDER_DISABLE", ignoreCase = true) -> {
+ geofenceProvider?.disable()
+ val response: MutableMap<String, Any> = HashMap()
+ response["action"] = "PROVIDER_DISABLE"
+ response["provider"] = "geofence"
+ notifyClient(response)
+ }
+ action.equals("GEOFENCE_REFRESH", ignoreCase = true) -> {
+ geofenceProvider?.refreshGeofences()
+ }
+ action.equals("GET_LOCATION", ignoreCase = true) -> {
+ geofenceProvider?.getLocation(
+ this@MainActivity,
+ object : GeofenceProvider.GeofenceCallback {
+ override fun accept(responseData: Map<String, Any>) {
+ notifyClient(responseData)
+ }
+ })
+ }
+ }
+ }
+
+ @Throws(JSONException::class)
+ private fun handlePushProviderMessage(data: JSONObject) {
+ val action = data.getString("action")
+ when {
+ action.equals("PROVIDER_INIT", ignoreCase = true) -> {
+ // Push permission is covered by the INTERNET permission and is not a runtime permission
+ val response: MutableMap<String, Any> = HashMap()
+ response["action"] = "PROVIDER_INIT"
+ response["provider"] = "push"
+ response["version"] = "fcm"
+ response["enabled"] = false
+ response["disabled"] = sharedPreferences!!.contains(PUSH_PROVIDER_DISABLED_KEY)
+ response["requiresPermission"] = false
+ response["hasPermission"] = true
+ response["success"] = true
+ notifyClient(response)
+ }
+ action.equals("PROVIDER_ENABLE", ignoreCase = true) -> {
+ val consoleId = data.getString("consoleId")
+ sharedPreferences!!.edit()
+ .putString(GeofenceProvider.Companion.consoleIdKey, consoleId)
+ .remove(PUSH_PROVIDER_DISABLED_KEY)
+ .apply()
+ // TODO: Implement topic support
+ FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener { task ->
+ val response: MutableMap<String, Any?> =
+ HashMap()
+ response["action"] = "PROVIDER_ENABLE"
+ response["provider"] = "push"
+ response["hasPermission"] = true
+ response["success"] = true
+ val responseData: MutableMap<String, Any> =
+ HashMap()
+ if (task.isSuccessful) {
+ responseData["token"] = task.result.token
+ }
+ response["data"] = responseData
+ notifyClient(response)
+ }
+ }
+ action.equals("PROVIDER_DISABLE", ignoreCase = true) -> {
+ // Cannot disable push notifications
+ val response: MutableMap<String, Any?> = HashMap()
+ response["action"] = "PROVIDER_DISABLE"
+ response["provider"] = "push"
+ sharedPreferences!!.edit().putBoolean(PUSH_PROVIDER_DISABLED_KEY, true).apply()
+ notifyClient(response)
+ }
+ }
+ }
+
+ @Throws(JSONException::class)
+ private fun handleStorageProviderMessage(data: JSONObject) {
+ val action = data.getString("action")
+ when {
+ action.equals("PROVIDER_INIT", ignoreCase = true) -> {
+ val response: MutableMap<String, Any> = HashMap()
+ response["action"] = "PROVIDER_INIT"
+ response["provider"] = "storage"
+ response["version"] = "1.0.0"
+ response["enabled"] = true
+ response["requiresPermission"] = false
+ response["hasPermission"] = true
+ response["success"] = true
+ notifyClient(response)
+ }
+ action.equals("PROVIDER_ENABLE", ignoreCase = true) -> {
+ // Doesn't require enabling but just in case it gets called lets return a valid response
+ val response: MutableMap<String, Any> = HashMap()
+ response["action"] = "PROVIDER_ENABLE"
+ response["provider"] = "storage"
+ response["hasPermission"] = true
+ response["success"] = true
+ notifyClient(response)
+ }
+ action.equals("STORE", ignoreCase = true) -> {
+ try {
+ val key = data.getString("key")
+ val valueJson = data.getString("value")
+ storeData(key, valueJson)
+ } catch (e: JSONException) {
+ LOG.log(Level.SEVERE, "Failed to store data", e)
+ }
+ }
+ action.equals("RETRIEVE", ignoreCase = true) -> {
+ try {
+ val key = data.getString("key")
+ val dataJson = retrieveData(key)
+ val response: MutableMap<String, Any?> = HashMap()
+ response["action"] = "RETRIEVE"
+ response["provider"] = "storage"
+ response["key"] = key
+ response["value"] = dataJson
+ notifyClient(response)
+ } catch (e: JSONException) {
+ LOG.log(Level.SEVERE, "Failed to retrieve data", e)
+ }
+ }
+ }
+ }
+
+ }
+
+ private fun notifyClient(data: Map<String, Any?>?) {
+ try {
+ val jsonString = ObjectMapper().writeValueAsString(data)
+ runOnUiThread {
+ webView.evaluateJavascript(
+ String.format(
+ "OpenRemoteConsole._handleProviderResponse('%s')",
+ jsonString
+ ), null
+ )
+ }
+ } catch (e: JsonProcessingException) {
+ e.printStackTrace()
+ }
+ }
+
+ private fun storeData(key: String?, data: String?) {
+ val editor = sharedPreferences!!.edit()
+ if (data == null) {
+ editor.remove(key)
+ } else {
+ editor.putString(key, data)
+ }
+ editor.apply()
+ }
+
+ private fun retrieveData(key: String?): String? {
+ return sharedPreferences!!.getString(key, null)
+ }
+
+ private fun onConnectivityChanged(connectivity: Boolean) {
+ LOG.info("Connectivity changed: $connectivity")
+ if (connectivity) {
+ reloadWebView()
+ } else {
+ Toast.makeText(this, "Check your connection", Toast.LENGTH_LONG).show()
+ }
+ }
+
+ private inner class ConnectivityChangeReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
+ val activeNetwork = cm.activeNetworkInfo
+ onConnectivityChanged(activeNetwork != null && activeNetwork.isConnectedOrConnecting)
+ }
+ }
+
+ companion object {
+ private val LOG = Logger.getLogger(
+ MainActivity::class.java.name
+ )
+ private const val WRITE_PERMISSION_FOR_DOWNLOAD = 999
+ private const val WRITE_PERMISSION_FOR_LOGGING = 1000
+ private const val WEBVIEW_LOAD_TIMEOUT_DEFAULT = 5000
+ const val ACTION_BROADCAST = "ACTION_BROADCAST"
+ const val PUSH_PROVIDER_DISABLED_KEY = "PushProviderDisabled"
+ const val CONSOLE_ID_KEY = "consoleId"
+ const val APP_CONFIG_KEY = "APP_CONFIG_KEY"
+ }
+}
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/ProjectActivity.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/ProjectActivity.kt
new file mode 100644
index 000000000..c8bb352fd
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/ProjectActivity.kt
@@ -0,0 +1,65 @@
+package io.openremote.app.ui
+
+import android.app.Activity
+import android.content.Intent
+import android.content.SharedPreferences
+import android.os.Bundle
+import android.view.View
+import android.view.inputmethod.EditorInfo
+import android.widget.Toast
+import androidx.preference.PreferenceManager
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import io.openremote.app.R
+import io.openremote.app.network.ApiManager
+import kotlinx.android.synthetic.main.activity_project.*
+
+class ProjectActivity : Activity() {
+ var sharedPreferences: SharedPreferences? = null
+
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_project)
+
+ sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
+
+ realm_input.setOnEditorActionListener { textView, actionId, keyEvent ->
+ if (actionId == EditorInfo.IME_ACTION_GO) {
+ if (!project_input.text.isNullOrBlank() && !realm_input.text.isNullOrBlank()) {
+ requestAppConfig(project_input.text.toString(), realm_input.text.toString())
+ }
+ true
+ } else {
+ false
+ }
+ }
+
+ connect_button.setOnClickListener {
+ if (!project_input.text.isNullOrBlank() && !realm_input.text.isNullOrBlank()) {
+ requestAppConfig(project_input.text.toString(), realm_input.text.toString())
+ }
+ }
+ }
+
+ private fun requestAppConfig(project: String, realm: String) {
+ progressBar.visibility = View.VISIBLE
+ val apiManager = ApiManager("https://${project}.openremote.io/api/${realm}")
+ apiManager.getAppConfig { statusCode, appConfig, error ->
+ progressBar.visibility = View.INVISIBLE
+ if (statusCode in 200..299) {
+ sharedPreferences?.edit()?.putString("project", project)?.apply()
+ sharedPreferences?.edit()?.putString("realm", realm)?.apply()
+ val intent = Intent(this@ProjectActivity, MainActivity::class.java)
+ intent.putExtra(MainActivity.APP_CONFIG_KEY, jacksonObjectMapper().writeValueAsString(appConfig))
+ startActivity(intent)
+ finish()
+ } else {
+ Toast.makeText(
+ this,
+ "Error occurred getting app config. Check your input and try again",
+ Toast.LENGTH_LONG
+ ).show()
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/SplashActivity.kt b/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/SplashActivity.kt
new file mode 100644
index 000000000..32d1b4a4e
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/java/io/openremote/app/ui/SplashActivity.kt
@@ -0,0 +1,43 @@
+package io.openremote.app.ui
+
+import android.app.Activity
+import android.content.Intent
+import android.content.SharedPreferences
+import android.os.Bundle
+import androidx.preference.PreferenceManager
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import io.openremote.app.R
+import io.openremote.app.network.ApiManager
+import io.openremote.app.ui.MainActivity.Companion.APP_CONFIG_KEY
+
+class SplashActivity : Activity() {
+ var sharedPreferences: SharedPreferences? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_splash)
+
+ sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
+
+ val project = sharedPreferences!!.getString("project", null)
+ val realm = sharedPreferences!!.getString("realm", null)
+
+ if (!project.isNullOrBlank() && !realm.isNullOrBlank()) {
+ val apiManager = ApiManager("https://${project}.openremote.io/api/$realm")
+ apiManager.getAppConfig { statusCode, appConfig, error ->
+ if (statusCode in 200..299) {
+ val intent = Intent(this@SplashActivity, MainActivity::class.java)
+ intent.putExtra(APP_CONFIG_KEY, jacksonObjectMapper().writeValueAsString(appConfig))
+ startActivity(intent)
+ finish()
+ } else {
+ startActivity(Intent(this@SplashActivity, ProjectActivity::class.java))
+ finish()
+ }
+ }
+ } else {
+ startActivity(Intent(this@SplashActivity, ProjectActivity::class.java))
+ finish()
+ }
+ }
+}
\ No newline at end of file
diff --git a/console/android/src/main/res/drawable-hdpi/ic_notification.png b/console/android/GenericApp/app/src/main/res/drawable-hdpi/ic_notification.png
similarity index 100%
rename from console/android/src/main/res/drawable-hdpi/ic_notification.png
rename to console/android/GenericApp/app/src/main/res/drawable-hdpi/ic_notification.png
diff --git a/console/android/src/main/res/drawable-mdpi/ic_notification.png b/console/android/GenericApp/app/src/main/res/drawable-mdpi/ic_notification.png
similarity index 100%
rename from console/android/src/main/res/drawable-mdpi/ic_notification.png
rename to console/android/GenericApp/app/src/main/res/drawable-mdpi/ic_notification.png
diff --git a/console/android/GenericApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/console/android/GenericApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
new file mode 100644
index 000000000..2b068d114
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
@@ -0,0 +1,30 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:aapt="http://schemas.android.com/aapt"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
+ <aapt:attr name="android:fillColor">
+ <gradient
+ android:endX="85.84757"
+ android:endY="92.4963"
+ android:startX="42.9492"
+ android:startY="49.59793"
+ android:type="linear">
+ <item
+ android:color="#44000000"
+ android:offset="0.0" />
+ <item
+ android:color="#00000000"
+ android:offset="1.0" />
+ </gradient>
+ </aapt:attr>
+ </path>
+ <path
+ android:fillColor="#FFFFFF"
+ android:fillType="nonZero"
+ android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
+ android:strokeWidth="1"
+ android:strokeColor="#00000000" />
+</vector>
\ No newline at end of file
diff --git a/console/android/src/main/res/drawable-xhdpi/ic_notification.png b/console/android/GenericApp/app/src/main/res/drawable-xhdpi/ic_notification.png
similarity index 100%
rename from console/android/src/main/res/drawable-xhdpi/ic_notification.png
rename to console/android/GenericApp/app/src/main/res/drawable-xhdpi/ic_notification.png
diff --git a/console/android/src/main/res/drawable-xxhdpi/ic_notification.png b/console/android/GenericApp/app/src/main/res/drawable-xxhdpi/ic_notification.png
similarity index 100%
rename from console/android/src/main/res/drawable-xxhdpi/ic_notification.png
rename to console/android/GenericApp/app/src/main/res/drawable-xxhdpi/ic_notification.png
diff --git a/console/android/src/main/res/drawable-xxxhdpi/ic_notification.png b/console/android/GenericApp/app/src/main/res/drawable-xxxhdpi/ic_notification.png
similarity index 100%
rename from console/android/src/main/res/drawable-xxxhdpi/ic_notification.png
rename to console/android/GenericApp/app/src/main/res/drawable-xxxhdpi/ic_notification.png
diff --git a/console/android/src/main/res/drawable/app_icon.xml b/console/android/GenericApp/app/src/main/res/drawable/app_icon.xml
similarity index 100%
rename from console/android/src/main/res/drawable/app_icon.xml
rename to console/android/GenericApp/app/src/main/res/drawable/app_icon.xml
diff --git a/console/android/GenericApp/app/src/main/res/drawable/cog.png b/console/android/GenericApp/app/src/main/res/drawable/cog.png
new file mode 100644
index 000000000..7d7d8c246
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/drawable/cog.png differ
diff --git a/console/android/src/main/res/drawable/empty.xml b/console/android/GenericApp/app/src/main/res/drawable/empty.xml
similarity index 100%
rename from console/android/src/main/res/drawable/empty.xml
rename to console/android/GenericApp/app/src/main/res/drawable/empty.xml
diff --git a/console/android/GenericApp/app/src/main/res/drawable/ic_launcher_background.xml b/console/android/GenericApp/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 000000000..07d5da9cb
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,170 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <path
+ android:fillColor="#3DDC84"
+ android:pathData="M0,0h108v108h-108z" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M9,0L9,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,0L19,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M29,0L29,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M39,0L39,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M49,0L49,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M59,0L59,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M69,0L69,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M79,0L79,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M89,0L89,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M99,0L99,108"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,9L108,9"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,19L108,19"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,29L108,29"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,39L108,39"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,49L108,49"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,59L108,59"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,69L108,69"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,79L108,79"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,89L108,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M0,99L108,99"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,29L89,29"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,39L89,39"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,49L89,49"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,59L89,59"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,69L89,69"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M19,79L89,79"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M29,19L29,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M39,19L39,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M49,19L49,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M59,19L59,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M69,19L69,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+ <path
+ android:fillColor="#00000000"
+ android:pathData="M79,19L79,89"
+ android:strokeWidth="0.8"
+ android:strokeColor="#33FFFFFF" />
+</vector>
diff --git a/console/android/GenericApp/app/src/main/res/drawable/ic_menu.xml b/console/android/GenericApp/app/src/main/res/drawable/ic_menu.xml
new file mode 100644
index 000000000..e1c8eb120
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/drawable/ic_menu.xml
@@ -0,0 +1,9 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportHeight="24.0"
+ android:viewportWidth="24.0">
+ <path
+ android:fillColor="#ffffff"
+ android:pathData="M3,18h18v-2L3,16v2zM3,13h18v-2L3,11v2zM3,6v2h18L21,6L3,6z" />
+</vector>
\ No newline at end of file
diff --git a/console/android/src/main/res/drawable/notification_icon.xml b/console/android/GenericApp/app/src/main/res/drawable/notification_icon.xml
similarity index 100%
rename from console/android/src/main/res/drawable/notification_icon.xml
rename to console/android/GenericApp/app/src/main/res/drawable/notification_icon.xml
diff --git a/console/android/GenericApp/app/src/main/res/drawable/or_app_icon.png b/console/android/GenericApp/app/src/main/res/drawable/or_app_icon.png
new file mode 100644
index 000000000..34fed749a
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/drawable/or_app_icon.png differ
diff --git a/console/android/GenericApp/app/src/main/res/drawable/or_logo.png b/console/android/GenericApp/app/src/main/res/drawable/or_logo.png
new file mode 100644
index 000000000..d7154867e
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/drawable/or_logo.png differ
diff --git a/console/android/GenericApp/app/src/main/res/drawable/or_push_icon.png b/console/android/GenericApp/app/src/main/res/drawable/or_push_icon.png
new file mode 100644
index 000000000..e1020884e
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/drawable/or_push_icon.png differ
diff --git a/console/android/GenericApp/app/src/main/res/drawable/or_splash.png b/console/android/GenericApp/app/src/main/res/drawable/or_splash.png
new file mode 100644
index 000000000..0464d21b3
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/drawable/or_splash.png differ
diff --git a/console/android/src/main/res/layout/activity_web.xml b/console/android/GenericApp/app/src/main/res/layout/activity_main.xml
similarity index 66%
rename from console/android/src/main/res/layout/activity_web.xml
rename to console/android/GenericApp/app/src/main/res/layout/activity_main.xml
index 80f165057..b2b8f4a37 100644
--- a/console/android/src/main/res/layout/activity_web.xml
+++ b/console/android/GenericApp/app/src/main/res/layout/activity_main.xml
@@ -1,19 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/activity_web"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="0dp"
- tools:context=".MainActivity">
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:id="@+id/activity_web"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:clipChildren="false"
+ android:clipToPadding="false"
+ android:padding="0dp"
+ tools:context=".ui.MainActivity">
<WebView
- android:id="@+id/webview"
+ android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true">
-
</WebView>
<ProgressBar
@@ -28,5 +30,4 @@
android:max="100"
android:progress="1"/>
- <include layout="@layout/error_layout"/>
</RelativeLayout>
diff --git a/console/android/GenericApp/app/src/main/res/layout/activity_project.xml b/console/android/GenericApp/app/src/main/res/layout/activity_project.xml
new file mode 100644
index 000000000..d54f50c9e
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/layout/activity_project.xml
@@ -0,0 +1,105 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@color/white"
+ android:padding="@dimen/box_inset_layout_padding"
+ tools:context=".ui.SplashActivity"
+ tools:deviceIds="wear">
+
+
+ <ImageView
+ android:id="@+id/imageView"
+ android:layout_width="0dp"
+ android:layout_height="240dp"
+ android:layout_marginStart="24dp"
+ android:layout_marginTop="24dp"
+ android:layout_marginEnd="24dp"
+ android:src="@drawable/or_logo"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toTopOf="parent" />
+
+ <TextView
+ android:id="@+id/textView"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="24dp"
+ android:layout_marginTop="32dp"
+ android:layout_marginEnd="24dp"
+ android:text="Connect to your application"
+ android:textAppearance="@style/TextAppearance.AppCompat.Large"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/imageView" />
+
+ <com.google.android.material.textfield.TextInputLayout
+ android:id="@+id/project_input_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="24dp"
+ android:layout_marginTop="24dp"
+ android:layout_marginEnd="24dp"
+ android:hint="Project"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/textView"
+ android:background="@color/bright_grey">
+
+ <com.google.android.material.textfield.TextInputEditText
+ android:id="@+id/project_input"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:singleLine="true"
+ android:imeOptions="actionNext"/>
+ </com.google.android.material.textfield.TextInputLayout>
+
+ <com.google.android.material.textfield.TextInputLayout
+ android:id="@+id/realm_input_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="24dp"
+ android:layout_marginTop="16dp"
+ android:layout_marginEnd="24dp"
+ android:hint="Realm"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/project_input_layout"
+ android:background="@color/bright_grey">
+
+ <com.google.android.material.textfield.TextInputEditText
+ android:id="@+id/realm_input"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:singleLine="true"
+ android:imeOptions="actionGo"/>
+ </com.google.android.material.textfield.TextInputLayout>
+
+ <Button
+ android:id="@+id/connect_button"
+ android:layout_width="100dp"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="24dp"
+ android:layout_marginEnd="24dp"
+ android:background="@color/colorPrimary"
+ android:text="Connect"
+ android:textColor="@color/white"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/realm_input_layout" />
+
+ <ProgressBar
+ android:id="@+id/progressBar"
+ style="@style/Widget.AppCompat.ProgressBar"
+ android:layout_width="48dp"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:background="@android:color/transparent"
+ android:visibility="invisible"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toTopOf="parent" />
+
+</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/res/layout/activity_splash.xml b/console/android/GenericApp/app/src/main/res/layout/activity_splash.xml
new file mode 100644
index 000000000..a8fab9698
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/layout/activity_splash.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@color/white"
+ android:padding="@dimen/box_inset_layout_padding"
+ tools:context=".ui.SplashActivity"
+ tools:deviceIds="wear">
+
+
+ <ImageView
+ android:id="@+id/imageView"
+ android:layout_width="240dp"
+ android:layout_height="240dp"
+ android:layout_marginStart="24dp"
+ android:layout_marginTop="24dp"
+ android:layout_marginEnd="24dp"
+ android:layout_marginBottom="24dp"
+ android:src="@drawable/or_splash"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toTopOf="parent" />
+
+
+
+</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/console/android/GenericApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
new file mode 100644
index 000000000..f4648418e
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ
diff --git a/console/android/GenericApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/console/android/GenericApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
new file mode 100644
index 000000000..34d62333b
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ
diff --git a/console/android/GenericApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/console/android/GenericApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
new file mode 100644
index 000000000..eadf4e618
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ
diff --git a/console/android/GenericApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/console/android/GenericApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
new file mode 100644
index 000000000..c4f34f813
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ
diff --git a/console/android/GenericApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/console/android/GenericApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
new file mode 100644
index 000000000..d854c0f84
Binary files /dev/null and b/console/android/GenericApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ
diff --git a/console/android/GenericApp/app/src/main/res/values/dimens.xml b/console/android/GenericApp/app/src/main/res/values/dimens.xml
new file mode 100644
index 000000000..1a7ba4a1a
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/values/dimens.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!--
+ Because the window insets on round devices are larger than 15dp, this padding only applies
+ to square screens.
+ -->
+ <dimen name="box_inset_layout_padding">0dp</dimen>
+
+ <!--
+ This padding applies to both square and round screens. The total padding between the buttons
+ and the window insets is box_inset_layout_padding (above variable) on square screens and
+ inner_frame_layout_padding (below variable) on round screens.
+ -->
+ <dimen name="inner_frame_layout_padding">5dp</dimen>
+</resources>
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/res/values/ic_launcher_background.xml b/console/android/GenericApp/app/src/main/res/values/ic_launcher_background.xml
new file mode 100644
index 000000000..c5d5899fd
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/values/ic_launcher_background.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_background">#FFFFFF</color>
+</resources>
\ No newline at end of file
diff --git a/console/android/GenericApp/app/src/main/res/xml/shortcuts.xml b/console/android/GenericApp/app/src/main/res/xml/shortcuts.xml
new file mode 100644
index 000000000..1933795ae
--- /dev/null
+++ b/console/android/GenericApp/app/src/main/res/xml/shortcuts.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <shortcut
+ android:enabled="true"
+ android:icon="@drawable/cog"
+ android:shortcutId="project"
+ android:shortcutShortLabel="@string/Project">
+ <intent
+ android:action="android.intent.action.VIEW"
+ android:targetClass="io.openremote.app.ui.SplashActivity"
+ android:targetPackage="io.openremote.app" />
+ <intent
+ android:action="CLEAR_SETTINGS"
+ android:targetClass="io.openremote.app.ui.ProjectActivity"
+ android:targetPackage="io.openremote.app" />
+ </shortcut>
+
+</shortcuts>
\ No newline at end of file
diff --git a/console/android/GenericApp/build.gradle b/console/android/GenericApp/build.gradle
new file mode 100644
index 000000000..eb61d111f
--- /dev/null
+++ b/console/android/GenericApp/build.gradle
@@ -0,0 +1,26 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+buildscript {
+ ext.kotlin_version = "1.4.10"
+ repositories {
+ google()
+ jcenter()
+ }
+ dependencies {
+ classpath "com.android.tools.build:gradle:4.0.2"
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ classpath 'com.google.gms:google-services:4.3.4'
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ jcenter()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
\ No newline at end of file
diff --git a/console/android/GenericApp/gradle.properties b/console/android/GenericApp/gradle.properties
new file mode 100644
index 000000000..4d15d015f
--- /dev/null
+++ b/console/android/GenericApp/gradle.properties
@@ -0,0 +1,21 @@
+# Project-wide Gradle settings.
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx2048m
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+# AndroidX package structure to make it clearer which packages are bundled with the
+# Android operating system, and which are packaged with your app"s APK
+# https://developer.android.com/topic/libraries/support-library/androidx-rn
+android.useAndroidX=true
+# Automatically convert third-party libraries to use AndroidX
+android.enableJetifier=true
+# Kotlin code style for this project: "official" or "obsolete":
+kotlin.code.style=official
\ No newline at end of file
diff --git a/console/android/gradle/wrapper/gradle-wrapper.properties b/console/android/GenericApp/gradle/wrapper/gradle-wrapper.properties
similarity index 80%
rename from console/android/gradle/wrapper/gradle-wrapper.properties
rename to console/android/GenericApp/gradle/wrapper/gradle-wrapper.properties
index b04c01163..dab9c1ef1 100644
--- a/console/android/gradle/wrapper/gradle-wrapper.properties
+++ b/console/android/GenericApp/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Tue Oct 31 15:17:22 CET 2017
+#Tue Oct 27 09:27:21 CET 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-bin.zip
diff --git a/console/android/GenericApp/settings.gradle b/console/android/GenericApp/settings.gradle
new file mode 100644
index 000000000..0279d6b9c
--- /dev/null
+++ b/console/android/GenericApp/settings.gradle
@@ -0,0 +1,2 @@
+include ':app'
+rootProject.name = "GenericApp"
\ No newline at end of file
diff --git a/console/android/README.md b/console/android/README.md
deleted file mode 100644
index 9f9035e57..000000000
--- a/console/android/README.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# OpenRemote v3 - Android Console
-
-Due to limitations of the Android development environment, this application is a separate, standalone project.
-
-## Building and running the application
-
-```
-./gradlew clean installDebug \
- && adb shell am start -n org.openremote.android.v3/org.openremote.android.MainActivity
-```
\ No newline at end of file
diff --git a/console/android/build.gradle b/console/android/build.gradle
deleted file mode 100644
index 3d7f9edb8..000000000
--- a/console/android/build.gradle
+++ /dev/null
@@ -1,69 +0,0 @@
-buildscript {
- repositories {
- google()
- jcenter()
- }
- dependencies {
- classpath "com.android.tools.build:gradle:$androidGradleVersion"
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
- }
-}
-
-allprojects {
- repositories {
- google()
- jcenter()
- }
-}
-
-apply plugin: "com.android.library"
-apply plugin: 'kotlin-android'
-
-version = projectVersion
-
-android {
- compileSdkVersion Integer.valueOf(androidCompileVersion)
-
- defaultConfig {
-
- minSdkVersion Integer.valueOf(androidMinVersion)
- targetSdkVersion Integer.valueOf(androidTargetVersion)
- versionCode Integer.valueOf(projectVersionCode)
- versionName project.version
- }
-
- packagingOptions {
- exclude "META-INF/DEPENDENCIES.txt"
- exclude "META-INF/LICENSE.txt"
- exclude "META-INF/NOTICE.txt"
- exclude "META-INF/NOTICE"
- exclude "META-INF/LICENSE"
- exclude "META-INF/DEPENDENCIES"
- exclude "META-INF/notice.txt"
- exclude "META-INF/license.txt"
- exclude "META-INF/dependencies.txt"
- exclude "META-INF/LGPL2.1"
- exclude "META-INF/LGPL2.1"
- }
-
- lintOptions {
- abortOnError false
- }
-
- buildTypes {
-
- }
-}
-
-dependencies {
- implementation "com.squareup.okhttp3:okhttp:$okhttp3Version"
- implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
- implementation "androidx.core:core:1.0.2"
- implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
- implementation "com.google.firebase:firebase-core:$firebaseCoreVersion"
- implementation "com.google.firebase:firebase-messaging:$fcmMessagingVersion"
- implementation "com.squareup.retrofit2:converter-jackson:$jacksonVersion"
- implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
- implementation "com.google.android.gms:play-services-location:$googlePlayVersion"
- implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
-}
diff --git a/console/android/gradle.properties b/console/android/gradle.properties
deleted file mode 100644
index 39316d8e7..000000000
--- a/console/android/gradle.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-org.gradle.jvmargs=-Xmx2g
-
-projectVersion = 3.0-SNAPSHOT
-
-# Increment this for every release
-projectVersionCode = 1
\ No newline at end of file
diff --git a/console/android/gradle/wrapper/gradle-wrapper.jar b/console/android/gradle/wrapper/gradle-wrapper.jar
deleted file mode 100644
index 13372aef5..000000000
Binary files a/console/android/gradle/wrapper/gradle-wrapper.jar and /dev/null differ
diff --git a/console/android/gradlew b/console/android/gradlew
deleted file mode 100755
index 9d82f7891..000000000
--- a/console/android/gradlew
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
- JAVACMD=`cygpath --unix "$JAVACMD"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/console/android/gradlew.bat b/console/android/gradlew.bat
deleted file mode 100644
index 8a0b282aa..000000000
--- a/console/android/gradlew.bat
+++ /dev/null
@@ -1,90 +0,0 @@
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
diff --git a/console/android/settings.gradle b/console/android/settings.gradle
deleted file mode 100644
index 6a1f051b4..000000000
--- a/console/android/settings.gradle
+++ /dev/null
@@ -1 +0,0 @@
-rootProject.name = "or-android"
\ No newline at end of file
diff --git a/console/android/src/androidTest/java/com/example/mymodule/app/ApplicationTest.java b/console/android/src/androidTest/java/com/example/mymodule/app/ApplicationTest.java
deleted file mode 100644
index 0ad0e0a73..000000000
--- a/console/android/src/androidTest/java/com/example/mymodule/app/ApplicationTest.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.example.mymodule.app;
-
-import android.app.Application;
-import android.test.ApplicationTestCase;
-
-/**
- * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
- */
-public class ApplicationTest extends ApplicationTestCase<Application> {
- public ApplicationTest() {
- super(Application.class);
- }
-}
\ No newline at end of file
diff --git a/console/android/src/debug/AndroidManifest.xml b/console/android/src/debug/AndroidManifest.xml
deleted file mode 100644
index 69ebb8b2c..000000000
--- a/console/android/src/debug/AndroidManifest.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.openremote.android">
-</manifest>
\ No newline at end of file
diff --git a/console/android/src/main/AndroidManifest.xml b/console/android/src/main/AndroidManifest.xml
deleted file mode 100644
index 531bb5bff..000000000
--- a/console/android/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.openremote.android">
-
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
- <uses-permission android:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
- <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-
- <application
- android:name=".MainApplication"
- android:allowBackup="true"
- android:icon="@drawable/app_icon"
- android:label="@string/OR_CONSOLE_NAME"
- android:theme="@style/OpenRemoteTheme">
-
- <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
- See README(https://goo.gl/l4GJaQ) for more. -->
- <meta-data
- android:name="com.google.firebase.messaging.default_notification_icon"
- android:resource="@drawable/ic_notification"/>
- <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
- notification message. See README(https://goo.gl/6BKBk7) for more. -->
- <meta-data
- android:name="com.google.firebase.messaging.default_notification_color"
- android:resource="@color/light_green"/>
-
- <meta-data android:name="google_analytics_adid_collection_enabled" android:value="false" />
-
-
- <service
- android:name="org.openremote.android.ORFirebaseMessagingService">
- <intent-filter>
- <action android:name="com.google.firebase.MESSAGING_EVENT"/>
- </intent-filter>
- </service>
-
- <service android:name="org.openremote.android.ORMessagingActionService">
-
- </service>
-
- <receiver android:name=".service.GeofenceBootCompleteReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED"/>
- </intent-filter>
- </receiver>
-
- <receiver
- android:name=".service.GeofenceTransitionsIntentService"
- android:enabled="true"
- android:exported="true"/>
-
- <!--<service -->
- <!--android:name=".service.GeofenceProvider$LocationService"-->
- <!--android:exported="false"/>-->
-
-
- </application>
-
-</manifest>
\ No newline at end of file
diff --git a/console/android/src/main/ic_launcher-web.png b/console/android/src/main/ic_launcher-web.png
deleted file mode 100644
index 3ea4366cd..000000000
Binary files a/console/android/src/main/ic_launcher-web.png and /dev/null differ
diff --git a/console/android/src/main/java/org/openremote/android/AndroidLoggingHandler.java b/console/android/src/main/java/org/openremote/android/AndroidLoggingHandler.java
deleted file mode 100644
index 8df64fd9b..000000000
--- a/console/android/src/main/java/org/openremote/android/AndroidLoggingHandler.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.openremote.android;
-
-import android.util.Log;
-import java.util.logging.*;
-
-/**
- * Make JUL work on Android.
- */
-public class AndroidLoggingHandler extends Handler {
-
- public static void reset(Handler rootHandler) {
- Logger rootLogger = LogManager.getLogManager().getLogger("");
- Handler[] handlers = rootLogger.getHandlers();
- for (Handler handler : handlers) {
- rootLogger.removeHandler(handler);
- }
- rootLogger.addHandler(rootHandler);
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public void flush() {
- }
-
- @Override
- public void publish(LogRecord record) {
- if (!super.isLoggable(record))
- return;
-
- String name = record.getLoggerName();
- int maxLength = 30;
- String tag = name.length() > maxLength ? name.substring(name.length() - maxLength) : name;
-
- try {
- int level = getAndroidLevel(record.getLevel());
- Log.println(level, tag, record.getMessage());
- if (record.getThrown() != null) {
- Log.println(level, tag, Log.getStackTraceString(record.getThrown()));
- }
- } catch (RuntimeException e) {
- Log.e("AndroidLoggingHandler", "Error logging message.", e);
- }
- }
-
- static int getAndroidLevel(Level level) {
- int value = level.intValue();
- if (value >= 1000) {
- return Log.ERROR;
- } else if (value >= 900) {
- return Log.WARN;
- } else if (value >= 800) {
- return Log.INFO;
- } else {
- return Log.DEBUG;
- }
- }
-}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/MainActivity.java b/console/android/src/main/java/org/openremote/android/MainActivity.java
deleted file mode 100644
index 4e59e2d02..000000000
--- a/console/android/src/main/java/org/openremote/android/MainActivity.java
+++ /dev/null
@@ -1,801 +0,0 @@
-package org.openremote.android;
-
-import android.Manifest;
-import android.annotation.SuppressLint;
-import android.annotation.TargetApi;
-import android.app.Activity;
-import android.app.DownloadManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.SharedPreferences;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.graphics.Bitmap;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.Uri;
-import android.net.http.SslError;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Environment;
-import android.os.Handler;
-import android.os.Looper;
-import android.preference.PreferenceManager;
-import android.text.TextUtils;
-import android.view.KeyEvent;
-import android.view.View;
-import android.webkit.ConsoleMessage;
-import android.webkit.CookieManager;
-import android.webkit.DownloadListener;
-import android.webkit.JavascriptInterface;
-import android.webkit.SslErrorHandler;
-import android.webkit.URLUtil;
-import android.webkit.WebChromeClient;
-import android.webkit.WebResourceError;
-import android.webkit.WebResourceRequest;
-import android.webkit.WebResourceResponse;
-import android.webkit.WebSettings;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.widget.Button;
-import android.widget.ProgressBar;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.android.gms.tasks.OnCompleteListener;
-import com.google.android.gms.tasks.Task;
-import com.google.firebase.iid.FirebaseInstanceId;
-import com.google.firebase.iid.InstanceIdResult;
-
-import org.jetbrains.annotations.NotNull;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.openremote.android.service.GeofenceProvider;
-import org.openremote.android.service.TokenService;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.RequiresApi;
-import androidx.core.app.ActivityCompat;
-import androidx.core.content.ContextCompat;
-
-public class MainActivity extends Activity {
-
- private static final Logger LOG = Logger.getLogger(MainActivity.class.getName());
-
- private static final int WRITE_PERMISSION_FOR_DOWNLOAD = 999;
- private static final int WRITE_PERMISSION_FOR_LOGGING = 1000;
- private static final int WEBVIEW_LOAD_TIMEOUT_DEFAULT = 5000;
-
- public static final String ACTION_BROADCAST = "ACTION_BROADCAST";
- public static final String PUSH_PROVIDER_DISABLED_KEY = "PushProviderDisabled";
- public static final String CONSOLE_ID_KEY = "consoleId";
-
- protected final ConnectivityChangeReceiver connectivityChangeReceiver = new ConnectivityChangeReceiver();
- protected WebView webView;
- protected Handler timeOutHandler;
- protected Runnable timeOutRunnable;
- protected ProgressBar progressBar;
- protected int webViewTimeout = WEBVIEW_LOAD_TIMEOUT_DEFAULT;
- protected boolean webViewLoaded;
- protected ErrorViewHolder errorViewHolder;
- protected SharedPreferences sharedPreferences;
- protected GeofenceProvider geofenceProvider;
- protected String consoleId;
- protected BroadcastReceiver onDownloadCompleteReciever = new BroadcastReceiver() {
- public void onReceive(Context ctxt, Intent intent) {
- String action = intent.getAction();
- if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
- Toast.makeText(getApplicationContext(), R.string.download_completed, Toast.LENGTH_LONG).show();
- }
- }
- };
-
- protected class ErrorViewHolder {
- View errorView;
- Button btnReload;
- Button btnExit;
- TextView tvErrorTitle;
- TextView tvErrorExplanation;
-
- public ErrorViewHolder(View errorView) {
- this.errorView = errorView;
- btnReload = errorView.findViewById(R.id.reload);
- btnExit = errorView.findViewById(R.id.exit);
- tvErrorTitle = errorView.findViewById(R.id.errorTitle);
- tvErrorExplanation = errorView.findViewById(R.id.errorExplanation);
- }
-
- public void show(int errorTitle, int errorDescription, boolean canReload, boolean canExit) {
- LOG.fine("Showing error view");
-
- btnReload.setVisibility(canReload ? View.VISIBLE : View.GONE);
- btnExit.setVisibility(canExit ? View.VISIBLE : View.GONE);
-
- tvErrorTitle.setText(errorTitle);
- tvErrorExplanation.setText(errorDescription);
- errorView.setVisibility(View.VISIBLE);
-
- // Stop and clear web view
- LOG.fine("Clearing web view");
- webView.loadUrl("about:blank");
- webView.setVisibility(View.GONE);
- }
-
- public void hide() {
- errorView.setVisibility(View.GONE);
- webView.setVisibility(View.VISIBLE);
- }
- }
-
- protected String getClientUrl() {
- String platform = "Android " + Build.VERSION.RELEASE;
- String name = getString(R.string.OR_CONSOLE_NAME);
- String providers = getString(R.string.OR_CONSOLE_PROVIDERS);
- String version = BuildConfig.VERSION_NAME;
-
- try {
- PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
- version = pInfo.versionName;
- } catch (PackageManager.NameNotFoundException e) {
- e.printStackTrace();
- }
-
- return getString(R.string.OR_BASE_SERVER) + getString(R.string.OR_CONSOLE_URL)
- + "?consolePlatform=" + platform
- + "&consoleName=" + name
- + "&consoleVersion=" + version
- + "&consoleProviders=" + providers;
- }
-
- @Override
- public void onActivityReenter(int resultCode, Intent data) {
- super.onActivityReenter(resultCode, data);
- }
-
- @SuppressWarnings("StatementWithEmptyBody")
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
-
- if (BuildConfig.DEBUG) {
- // Check write permission for logging purposes
-
- String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
- if (ContextCompat.checkSelfPermission(getApplicationContext(), writePermission) != PackageManager.PERMISSION_GRANTED) {
- // Write permission has not been granted yet, request it.
- ActivityCompat.requestPermissions(this, new String[]{writePermission}, WRITE_PERMISSION_FOR_LOGGING);
- } else {
- // Assume logging has already been initialised by main application
- }
- }
-
- try {
- String timeoutStr = getString(R.string.OR_CONSOLE_LOAD_TIMEOUT);
- webViewTimeout = Integer.parseInt(timeoutStr);
- } catch (NumberFormatException nfe) {
- System.out.println("Could not parse console load timeout value: " + nfe);
- }
-
- // Enable remote debugging of WebView from Chrome Debugger tools
- if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) {
- LOG.info("Enabling remote debugging");
- WebView.setWebContentsDebuggingEnabled(true);
- }
-
- setContentView(R.layout.activity_web);
-
- webView = findViewById(R.id.webview);
- if (savedInstanceState != null) {
- webView.restoreState(savedInstanceState);
- } else {
- initializeWebView();
- }
- openIntentUrl(getIntent());
-
- progressBar = findViewById(R.id.webProgressBar);
- progressBar.setMax(100);
- progressBar.setProgress(1);
-
- errorViewHolder = new ErrorViewHolder(findViewById(R.id.errorView));
- }
-
- @Override
- protected void onNewIntent(Intent intent) {
- openIntentUrl(intent);
- }
-
- protected void openIntentUrl(Intent intent) {
- if (!intent.hasExtra("appUrl")) {
- String url = getClientUrl();
- LOG.fine("Loading web view: " + url);
- loadUrl(url);
- } else {
- String url = getClientUrl();
- String intentUrl = intent.getStringExtra("appUrl");
- if (intentUrl != null) {
- if (intentUrl.startsWith("http") || intentUrl.startsWith("https")) {
- url = intentUrl;
- } else {
- url = url + intentUrl;
- }
- }
-
- LOG.fine("Loading web view: " + url);
- loadUrl(url);
- }
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- registerReceiver(connectivityChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
- registerReceiver(onDownloadCompleteReciever, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- unregisterReceiver(connectivityChangeReceiver);
- unregisterReceiver(onDownloadCompleteReciever);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (webView != null) {
- if (event.getAction() == KeyEvent.ACTION_DOWN) {
- switch (keyCode) {
- case KeyEvent.KEYCODE_BACK:
- if (webView.canGoBack()) {
- webView.goBack();
- } else {
- finish();
- }
- return true;
- }
- }
- }
- return super.onKeyDown(keyCode, event);
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- webView.saveState(outState);
- }
-
- public void reloadWebView(View view) {
- errorViewHolder.hide();
- String url = webView.getUrl();
- if ("about:blank".equals(url)) {
- url = getClientUrl();
- LOG.fine("Reloading web view: " + url);
- loadUrl(url);
- }
- }
-
- public void exitOnClick(View view) {
- finish();
- System.exit(0);
- }
-
- @SuppressLint("SetJavaScriptEnabled")
- protected void initializeWebView() {
- LOG.fine("Initializing web view");
-
- final WebAppInterface webAppInterface = new WebAppInterface(this, webView);
-
- webView.addJavascriptInterface(webAppInterface, "MobileInterface");
- WebSettings webSettings = webView.getSettings();
- webSettings.setJavaScriptEnabled(true);
- webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
- webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
- webSettings.setDomStorageEnabled(true);
- webSettings.setDatabaseEnabled(true);
- webSettings.setSupportMultipleWindows(true);
- webView.setOnLongClickListener(new View.OnLongClickListener() {
- @Override
- public boolean onLongClick(View v) {
- return true;
- }
- });
- webView.setLongClickable(false);
-
- webView.setWebViewClient(new WebViewClient() {
-
- @Override
- public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
-
- // When initialising Keycloak with an invalid offline refresh token (e.g. wrong nonce because
- // server was reinstalled), we detect the failure and then don't show an error view. We clear the stored
- // invalid token. The web app will then start a new login.
- if (request.getUrl().getLastPathSegment() != null &&
- request.getUrl().getLastPathSegment().equals("token") &&
- request.getMethod().equals("POST") &&
- errorResponse.getStatusCode() == 400) {
- MainActivity.this.storeData(getString(R.string.SHARED_PREF_REFRESH_TOKEN), null);
- return;
- }
-
- handleError(errorResponse.getStatusCode(), errorResponse.getReasonPhrase(), request.getUrl().toString(), request.isForMainFrame());
- }
-
- @Override
- public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
- if (Boolean.parseBoolean(getString(R.string.SSL_IGNORE))) {
- LOG.fine("Ignoring SSL certificate error: " + error.getPrimaryError());
- handler.proceed(); // Ignore SSL certificate errors
- } else {
- LOG.severe("SSL error: " + error.getPrimaryError());
- LOG.severe("SSL certificate: " + error.getCertificate());
- errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
- }
- }
-
- @SuppressWarnings("deprecation")
- @Override
- public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
- handleError(errorCode, description, failingUrl, true);
- }
-
- @TargetApi(Build.VERSION_CODES.M)
- @Override
- public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
-
- // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
- if ("net::ERR_CACHE_MISS".contentEquals(error.getDescription())) {
- return;
- }
-
- if (request.getUrl().toString().equals("about:blank") && error.getErrorCode() == ERROR_UNSUPPORTED_SCHEME) {
- return;
- }
-
- handleError(
- error.getErrorCode(), error.getDescription().toString(),
- request.getUrl().toString(), request.isForMainFrame());
- }
-
- @Override
- public void onPageStarted(WebView view, final String url, Bitmap favicon) {
-
- progressBar.setVisibility(View.VISIBLE);
-
- timeOutRunnable = new Runnable() {
- public void run() {
- if (!webViewLoaded) {
- handleError(ERROR_TIMEOUT, "Connection timed out", url, true);
- }
- }
- };
- timeOutHandler = new Handler(Looper.myLooper());
- timeOutHandler.postDelayed(timeOutRunnable, 5000);
- }
-
- @Override
- public void onPageFinished(WebView view, String url) {
- webViewLoaded = true;
- progressBar.setVisibility(View.GONE);
- timeOutHandler.removeCallbacks(timeOutRunnable);
- }
-
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- Uri uri = Uri.parse(url);
- if (uri.getScheme().equalsIgnoreCase("webbrowser")) {
- String newUrl = uri.buildUpon().scheme("https").build().toString();
- Intent i = new Intent(Intent.ACTION_VIEW);
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- i.setData(Uri.parse(newUrl));
- startActivity(i);
- return true;
- }
- return super.shouldOverrideUrlLoading(view, url);
- }
-
- @Override
- @RequiresApi(Build.VERSION_CODES.N)
- public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
- if (request.getUrl().getScheme().equalsIgnoreCase("webbrowser")) {
- String newUrl = request.getUrl().buildUpon().scheme("https").build().toString();
- Intent i = new Intent(Intent.ACTION_VIEW);
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- i.setData(Uri.parse(newUrl));
- startActivity(i);
- return true;
- }
- return super.shouldOverrideUrlLoading(view, request);
- }
-
- protected void handleError(int errorCode, String description, String failingUrl, boolean isForMainFrame) {
-
- LOG.warning("Error requesting '" + failingUrl + "': " + errorCode + "(" + description + ")");
-
- // This will be the URL loaded into the webview itself (false for images etc. of the main page)
- if (isForMainFrame) {
-
- // Check page load error URL
- String errorUrl = getString(R.string.OR_CONSOLE_LOAD_ERROR_URL);
- if (!TextUtils.isEmpty(errorUrl) && !Objects.equals(failingUrl, errorUrl)) {
- LOG.info("Loading error URL: " + errorUrl);
- loadUrl(errorUrl);
- return;
- }
- } else {
-
- if (Boolean.parseBoolean(getString(R.string.OR_CONSOLE_IGNORE_PAGE_ERRORS))) {
- return;
- }
-
- //TODO should we always ignore image errors?
- if (failingUrl != null && (failingUrl.endsWith("png")
- || failingUrl.endsWith("jpg")
- || failingUrl.endsWith("ico"))) {
- LOG.info("Ignoring error loading image resource");
- return;
- }
- }
-
- errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
- }
- });
-
- webView.setWebChromeClient(new WebChromeClient() {
- @Override
- public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
- String msg = "WebApp console (" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + "): " + consoleMessage.message();
- switch (consoleMessage.messageLevel()) {
- case DEBUG:
- case TIP:
- LOG.fine(msg);
- break;
- case LOG:
- LOG.info(msg);
- break;
- default:
- LOG.severe(msg);
- }
- return true;
- }
-
- public void onProgressChanged(WebView view, int progress) {
- progressBar.setProgress(progress);
- }
-
- @Override
- public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
- {
- WebView newWebView = new WebView(MainActivity.this);
- view.addView(newWebView);
- WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
- transport.setWebView(newWebView);
- resultMsg.sendToTarget();
-
- newWebView.setWebViewClient(new WebViewClient() {
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- Intent browserIntent = new Intent(Intent.ACTION_VIEW);
- browserIntent.setData(Uri.parse(url));
- startActivity(browserIntent);
- return true;
- }
- });
- return true;
- }
- });
-
- webView.setDownloadListener(new DownloadListener() {
- @Override
- public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
-
- String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
- if (ContextCompat.checkSelfPermission(MainActivity.this, writePermission) != PackageManager.PERMISSION_GRANTED) {
- // Write permission has not been granted yet, request it.
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{writePermission}, WRITE_PERMISSION_FOR_DOWNLOAD);
- } else {
- DownloadManager.Request request = new
- DownloadManager.Request(Uri.parse(url));
-
- request.setMimeType(mimetype);
- //------------------------COOKIE!!------------------------
- String cookies = CookieManager.getInstance().getCookie(url);
- request.addRequestHeader("cookie", cookies);
- //------------------------COOKIE!!------------------------
- request.addRequestHeader("User-Agent", userAgent);
- request.setDescription("Downloading file...");
- request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
- request.allowScanningByMediaScanner();
- request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
- request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
- DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
- if (dm != null) {
- Toast.makeText(getApplicationContext(), R.string.downloading_file, Toast.LENGTH_LONG).show();
- dm.enqueue(request);
- } else {
- Toast.makeText(getApplicationContext(), R.string.error_downloading, Toast.LENGTH_LONG).show();
- }
- }
- }
- });
- }
-
- protected void loadUrl(String url) {
- webViewLoaded = false;
- webView.loadUrl(url);
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (requestCode == WRITE_PERMISSION_FOR_LOGGING) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- // Add File logging
- MainApplication.addFileHandler(this);
- }
- } else if (requestCode == WRITE_PERMISSION_FOR_DOWNLOAD) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- Toast.makeText(getApplicationContext(), R.string.downloading_file, Toast.LENGTH_LONG).show();
- }
- } else if (requestCode == GeofenceProvider.Companion.getLocationReponseCode()) {
- geofenceProvider.onRequestPermissionsResult(requestCode, permissions, grantResults);
- } else {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- }
- }
-
- protected class WebAppInterface {
-
- private final Activity activity;
- private final TokenService tokenService;
- private final WebView webView;
-
- public WebAppInterface(Activity activity, WebView webView) {
- tokenService = new TokenService(activity);
- this.activity = activity;
- this.webView = webView;
- }
-
- @JavascriptInterface
- public void postMessage(String jsonMessage) throws JSONException {
- JSONObject reader = new JSONObject(jsonMessage);
- String messageType = reader.getString("type");
- JSONObject data = reader.optJSONObject("data");
- switch (messageType) {
- case "error":
- LOG.fine("Received WebApp message, error: " + data.getString("error"));
- Handler mainHandler = new Handler(getMainLooper());
- mainHandler.post(new Runnable() {
- @Override
- public void run() {
- errorViewHolder.show(R.string.fatalError, R.string.fatalErrorExplain, true, true);
- }
- });
- break;
- case "provider":
- String action = data.getString("action");
- if (action != null) {
- String provider = data.getString("provider");
- if (provider.equalsIgnoreCase("geofence")) {
- handleGeofenceProviderMessage(data);
- } else if (provider.equalsIgnoreCase("push")) {
- handlePushProviderMessage(data);
- } else if (provider.equalsIgnoreCase("storage")) {
- handleStorageProviderMessage(data);
- }
- }
- break;
- default:
- }
- }
-
- protected void handleGeofenceProviderMessage(JSONObject data) throws JSONException {
- String action = data.getString("action");
-
- if (geofenceProvider == null) {
- geofenceProvider = new GeofenceProvider(activity);
- }
-
- if (action.equalsIgnoreCase("PROVIDER_INIT")) {
- Map<String, Object> initData = geofenceProvider.initialize();
- notifyClient(initData);
- } else if (action.equalsIgnoreCase("PROVIDER_ENABLE")) {
- String consoleId = data.getString("consoleId");
-
- if (consoleId != null) {
- ((MainActivity) activity).consoleId = consoleId;
- geofenceProvider.enable(MainActivity.this, String.format("%s/api/%s",
- getString(R.string.OR_BASE_SERVER),
- getString(R.string.OR_REALM)),
- consoleId, new GeofenceProvider.GeofenceCallback() {
- @Override
- public void accept(@NotNull Map<String, ?> responseData) {
- //noinspection unchecked
- notifyClient((Map<String, Object>) responseData);
- }
- });
- }
- } else if (action.equalsIgnoreCase("PROVIDER_DISABLE")) {
- geofenceProvider.disable();
- Map<String, Object> response = new HashMap<>();
- response.put("action", "PROVIDER_DISABLE");
- response.put("provider", "geofence");
- notifyClient(response);
- } else if (action.equalsIgnoreCase("GEOFENCE_REFRESH")) {
- geofenceProvider.refreshGeofences();
- } else if (action.equalsIgnoreCase("GET_LOCATION")) {
- geofenceProvider.getLocation(MainActivity.this, new GeofenceProvider.GeofenceCallback() {
- @Override
- public void accept(@NotNull Map<String, ?> responseData) {
- //noinspection unchecked
- notifyClient((Map<String, Object>) responseData);
- }
- });
- }
- }
-
- protected void handlePushProviderMessage(JSONObject data) throws JSONException {
- String action = data.getString("action");
-
- if (action.equalsIgnoreCase("PROVIDER_INIT")) {
- // Push permission is covered by the INTERNET permission and is not a runtime permission
- Map<String, Object> response = new HashMap<>();
- response.put("action", "PROVIDER_INIT");
- response.put("provider", "push");
- response.put("version", "fcm");
- response.put("enabled", false);
- response.put("disabled", sharedPreferences.contains(PUSH_PROVIDER_DISABLED_KEY));
- response.put("requiresPermission", false);
- response.put("hasPermission", true);
- response.put("success", true);
- notifyClient(response);
- } else if (action.equalsIgnoreCase("PROVIDER_ENABLE")) {
- String consoleId = data.getString("consoleId");
-
- if (consoleId != null) {
- sharedPreferences.edit()
- .putString(GeofenceProvider.Companion.getConsoleIdKey(), consoleId)
- .remove(PUSH_PROVIDER_DISABLED_KEY)
- .apply();
- }
- // TODO: Implement topic support
- FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
- @Override
- public void onComplete(@NonNull Task<InstanceIdResult> task) {
- Map<String, Object> response = new HashMap<>();
- response.put("action", "PROVIDER_ENABLE");
- response.put("provider", "push");
- response.put("hasPermission", true);
- response.put("success", true);
- Map<String, Object> responseData = new HashMap<>();
- if (task.isSuccessful()) {
- responseData.put("token", task.getResult().getToken());
- }
- response.put("data", responseData);
- notifyClient(response);
- }
- });
-
- } else if (action.equalsIgnoreCase("PROVIDER_DISABLE")) {
- // Cannot disable push notifications
- Map<String, Object> response = new HashMap<>();
- response.put("action", "PROVIDER_DISABLE");
- response.put("provider", "push");
- sharedPreferences.edit().putBoolean(PUSH_PROVIDER_DISABLED_KEY, true).apply();
- notifyClient(response);
- }
- }
-
- protected void handleStorageProviderMessage(JSONObject data) throws JSONException {
- String action = data.getString("action");
-
- if (action.equalsIgnoreCase("PROVIDER_INIT")) {
- Map<String, Object> response = new HashMap<>();
- response.put("action", "PROVIDER_INIT");
- response.put("provider", "storage");
- response.put("version", "1.0.0");
- response.put("enabled", true);
- response.put("requiresPermission", false);
- response.put("hasPermission", true);
- response.put("success", true);
- notifyClient(response);
- } else if (action.equalsIgnoreCase("PROVIDER_ENABLE")) {
- // Doesn't require enabling but just in case it gets called lets return a valid response
- Map<String, Object> response = new HashMap<>();
- response.put("action", "PROVIDER_ENABLE");
- response.put("provider", "storage");
- response.put("hasPermission", true);
- response.put("success", true);
- notifyClient(response);
- } else if (action.equalsIgnoreCase("STORE")) {
- try {
- String key = data.getString("key");
- String valueJson = data.getString("value");
- storeData(key, valueJson);
- } catch (JSONException e) {
- LOG.log(Level.SEVERE, "Failed to store data", e);
- }
- } else if (action.equalsIgnoreCase("RETRIEVE")) {
- try {
- String key = data.getString("key");
- String dataJson = retrieveData(key);
- Map<String, Object> response = new HashMap<>();
- response.put("action", "RETRIEVE");
- response.put("provider", "storage");
- response.put("key", key);
- response.put("value", dataJson);
- notifyClient(response);
- } catch (JSONException e) {
- LOG.log(Level.SEVERE, "Failed to retrieve data", e);
- }
- }
- }
- }
-
- protected void notifyClient(Map<String, Object> data) {
- try {
- final String jsonString = new ObjectMapper().writeValueAsString(data);
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- webView.evaluateJavascript(String.format("OpenRemoteConsole._handleProviderResponse('%s')", jsonString), null);
- }
- });
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
- }
-
- protected void storeData(String key, String data) {
- SharedPreferences.Editor editor = sharedPreferences.edit();
- if (data == null) {
- editor.remove(key);
- } else {
- editor.putString(key, data);
- }
- editor.apply();
- }
-
- protected String retrieveData(String key) {
- return sharedPreferences.getString(key, null);
- }
-
- protected void onConnectivityChanged(boolean connectivity) {
- LOG.info("Connectivity changed: " + connectivity);
- // TODO Should check if about:blank && connectivity == true, otherwise no reload necessary
- if (connectivity) {
- reloadWebView(getCurrentFocus());
- } else {
- errorViewHolder.show(R.string.noConnectivity, R.string.noConnectivityExplain, false, true);
- }
- }
-
- protected class ConnectivityChangeReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- ConnectivityManager cm
- = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
-
- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
- onConnectivityChanged(activeNetwork != null && activeNetwork.isConnectedOrConnecting());
- }
- }
-}
-
-
diff --git a/console/android/src/main/java/org/openremote/android/MainApplication.java b/console/android/src/main/java/org/openremote/android/MainApplication.java
deleted file mode 100644
index 1848cecdd..000000000
--- a/console/android/src/main/java/org/openremote/android/MainApplication.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package org.openremote.android;
-
-import android.Manifest;
-import android.app.Application;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.media.MediaScannerConnection;
-import android.os.Environment;
-import androidx.core.content.ContextCompat;
-
-import java.io.File;
-import java.util.logging.*;
-
-public class MainApplication extends Application {
-
- @Override
- public void onCreate() {
- super.onCreate();
-
- // Fix and configure JUL
- AndroidLoggingHandler.reset(new AndroidLoggingHandler());
-
- if (BuildConfig.DEBUG) {
- java.util.logging.Logger.getLogger("org.openremote").setLevel(Level.FINEST);
- java.util.logging.Logger.getLogger("io.openremote").setLevel(Level.FINEST);
-
- // Get write permission
- String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
- if (ContextCompat.checkSelfPermission(getApplicationContext(), writePermission) == PackageManager.PERMISSION_GRANTED) {
- addFileHandler(getApplicationContext());
- }
- }
-
- Logger LOG = Logger.getLogger(MainApplication.class.getName());
- LOG.info(">>> Starting OpenRemote application");
- }
-
- static void addFileHandler(Context context) {
-
- try {
-
- File logDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "openremote");
-
- if (!logDirectory.exists() && !logDirectory.mkdirs()) {
- throw new Exception("Failed to make log directory");
- }
-
- String logFilePattern = logDirectory.getAbsolutePath() + File.separator + "openremote.log";
-
- FileHandler fileHandler = null;
- fileHandler = new FileHandler(logFilePattern, 10000000, 10, true);
- fileHandler.setFormatter(new SimpleFormatter());
- Logger rootLogger = LogManager.getLogManager().getLogger("");
- rootLogger.addHandler(fileHandler);
-
- rootLogger.info("Added logging file handler");
-
- // Force scan of first log file as might not show via MTP otherwise
- MediaScannerConnection.scanFile(
- context,
- new String[]{logFilePattern + ".0"},
- null,
- null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
deleted file mode 100644
index 668f0ebbd..000000000
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ /dev/null
@@ -1,219 +0,0 @@
-package org.openremote.android;
-
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.media.RingtoneManager;
-import android.net.Uri;
-import android.os.Build;
-import androidx.annotation.RequiresApi;
-import androidx.core.app.NotificationCompat;
-import android.text.TextUtils;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.firebase.iid.FirebaseInstanceId;
-import com.google.firebase.messaging.RemoteMessage;
-import org.openremote.android.service.AlertAction;
-import org.openremote.android.service.AlertButton;
-import org.openremote.android.service.GeofenceProvider;
-import org.openremote.android.service.TokenService;
-
-import java.util.Date;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class ORFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
-
- private static final Logger LOG = Logger.getLogger(ORFirebaseMessagingService.class.getName());
-
- private final String NOTICATION_CHANNEL_ID = BuildConfig.APPLICATION_ID + ".OREindhovenMessage";
-
- private TokenService tokenService;
-
- public class MyBroadcastReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- LOG.info("TODO: Remove notification");
- }
-
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- tokenService = new TokenService(getApplicationContext());
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- createNotificationChannel();
- }
- }
-
- /**
- * Called when message is received.
- *
- * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
- */
- // [START receive_message]
- @Override
- public void onMessageReceived(RemoteMessage remoteMessage) {
- // [START_EXCLUDE]
- // There are two types of messages data messages and notification messages. Data messages are handled
- // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
- // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
- // is in the foreground. When the app is in the background an automatically generated notification is displayed.
- // When the user taps on the notification they are returned to the app. Messages containing both notification
- // and data payloads are treated as notification messages. The Firebase console always sends notification
- // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
- // [END_EXCLUDE]
-
- // TODO(developer): Handle FCM messages here.
- // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
- LOG.fine("Received message from: " + remoteMessage.getFrom());
-
- // If the message contains a notification then we assume it has been shown to the user
- if (remoteMessage.getNotification() != null) {
- LOG.fine("Message contains notification body: " + remoteMessage.getNotification().getBody());
- } else if (remoteMessage.getData() != null && !remoteMessage.getData().isEmpty()) {
-
- Map<String, String> messageData = remoteMessage.getData();
-
- // Mark as delivered on the server
- String notificationIdStr = messageData.get("notification-id");
- Long notificationId = null;
-
- if (notificationIdStr != null && !notificationIdStr.isEmpty()) {
- notificationId = Long.parseLong(notificationIdStr);
- String consoleId = getSharedPreferences(getApplicationContext().getString(R.string.OR_CONSOLE_NAME), Context.MODE_PRIVATE).getString("consoleId", "");
- if (!TextUtils.isEmpty(consoleId)) {
- tokenService.notificationDelivered(notificationId, consoleId);
- }
- }
-
- boolean isSilent = !messageData.containsKey("or-title");
-
- if (isSilent) {
- String action = remoteMessage.getData().get("action");
-
- switch (action) {
- case "GEOFENCE_REFRESH":
- GeofenceProvider geofenceProvider = new GeofenceProvider(getApplicationContext());
- geofenceProvider.refreshGeofences();
- break;
- default:
- Intent broadCastIntent = new Intent(MainActivity.ACTION_BROADCAST);
- broadCastIntent.putExtra("action", action);
- sendBroadcast(broadCastIntent);
- break;
- }
- } else {
-
- String title = messageData.get("or-title");
- String body = messageData.get("or-body");
- AlertButton[] buttons = null;
- AlertAction action = null;
-
- // Check for action (to be executed when notification is clicked)
- if (messageData.containsKey("action")) {
- String actionJson = messageData.get("action");
-
- if (actionJson != null && !actionJson.isEmpty()) {
- try {
- action = new ObjectMapper().readValue(actionJson, AlertAction.class);
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to de-serialise alert action", e);
- }
- }
- }
-
- // Check for buttons
- if (messageData.containsKey("buttons")) {
- String buttonsJson = messageData.get("buttons");
-
- if (buttonsJson != null && !buttonsJson.isEmpty()) {
- try {
- buttons = new ObjectMapper().readValue(buttonsJson, AlertButton[].class);
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to de-serialise alert actions", e);
- }
- }
- }
-
- handleNotification(notificationId, title, body, action, buttons);
- }
- }
- }
-
- @Override
- public void onNewToken(String s) {
- super.onNewToken(s);
- tokenService.sendOrStoreFCMToken(s, FirebaseInstanceId.getInstance().getId());
- }
-
- @RequiresApi(Build.VERSION_CODES.O)
- private void createNotificationChannel() {
- String channelName = "OR Eindhoven Message Service";
- NotificationChannel channel = new NotificationChannel(NOTICATION_CHANNEL_ID,
- channelName, NotificationManager.IMPORTANCE_HIGH);
- channel.setShowBadge(false);
- NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- service.createNotificationChannel(channel);
- }
-
- private void handleNotification(Long notificationId, String title, String body, AlertAction action, AlertButton[] buttons) {
- Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
-
- NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTICATION_CHANNEL_ID)
- .setContentTitle(title)
- .setWhen(new Date().getTime())
- .setShowWhen(true)
- .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
- .setContentText(body)
- .setSmallIcon(R.drawable.notification_icon)
- .setWhen(0)
- .setPriority(Notification.PRIORITY_MAX)
- .setSound(defaultSoundUri)
- .setDeleteIntent(createActionIntent(notificationId, "\"CLOSED\"", null));
-
- if (action != null) {
- notificationBuilder.setContentIntent(createActionIntent(notificationId, null, action));
- }
-
- if (buttons != null) {
- for (AlertButton alertButton : buttons) {
- notificationBuilder.addAction(
- new NotificationCompat.Action(R.drawable.empty,
- alertButton.getTitle(),
- createActionIntent(notificationId, alertButton.getTitle(), alertButton.getAction())));
- }
- }
-
- LOG.fine("Showing notification id=" + notificationId + ", title=" + title + ", body=" + body + ", action=" + action + ", buttons=" +(buttons != null ? buttons.length : 0));
-
- NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- if (notificationManager != null) {
- notificationManager.notify(notificationId.hashCode(), notificationBuilder.build());
- }
- }
-
- private PendingIntent createActionIntent(Long notificationId, String acknowledgement, AlertAction alertAction) {
-
- Intent actionIntent = new Intent(this, ORMessagingActionService.class);
- actionIntent.putExtra("notificationId", notificationId);
- actionIntent.putExtra("acknowledgement", acknowledgement);
- actionIntent.setAction(Long.toString(System.currentTimeMillis()));
-
- if (alertAction != null && alertAction.getUrl() != null && !alertAction.getUrl().isEmpty()) {
- actionIntent.putExtra("appUrl", alertAction.getUrl());
- actionIntent.putExtra("httpMethod", alertAction.getHttpMethod());
- actionIntent.putExtra("silent", alertAction.isSilent());
- actionIntent.putExtra("openInBrowser", alertAction.isOpenInBrowser());
- actionIntent.putExtra("data", alertAction.getDataJson());
- }
-
- return PendingIntent.getService(this, 0, actionIntent, PendingIntent.FLAG_ONE_SHOT);
- }
-}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/AlertAction.java b/console/android/src/main/java/org/openremote/android/service/AlertAction.java
deleted file mode 100644
index c742f2ad1..000000000
--- a/console/android/src/main/java/org/openremote/android/service/AlertAction.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package org.openremote.android.service;
-
-import com.fasterxml.jackson.databind.JsonNode;
-
-import java.io.Serializable;
-
-public class AlertAction implements Serializable {
- private String url;
- private String httpMethod;
- private JsonNode data;
- private boolean silent;
- private boolean openInBrowser;
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getHttpMethod() {
- return httpMethod;
- }
-
- public void setHttpMethod(String httpMethod) {
- this.httpMethod = httpMethod;
- }
-
- public JsonNode getData() {
- return data;
- }
-
- public void setData(JsonNode data) {
- this.data = data;
- }
-
- public String getDataJson() {
- return data == null ? null : data.toString();
- }
-
- public boolean isSilent() {
- return silent;
- }
-
- public void setSilent(boolean silent) {
- this.silent = silent;
- }
-
- public boolean isOpenInBrowser() {
- return openInBrowser;
- }
-
- public void setOpenInBrowser(boolean openInBrowser) {
- this.openInBrowser = openInBrowser;
- }
-
- @Override
- public String toString() {
- return "AlertAction{" +
- "url=" + url +
- ", httpMethod=" + httpMethod +
- ", data=" + data +
- ", silent=" + silent +
- ", openInBrowser=" + openInBrowser +
- '}';
- }
-}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/AlertButton.java b/console/android/src/main/java/org/openremote/android/service/AlertButton.java
deleted file mode 100644
index 138d67e5a..000000000
--- a/console/android/src/main/java/org/openremote/android/service/AlertButton.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.openremote.android.service;
-
-import java.io.Serializable;
-
-public class AlertButton implements Serializable {
- private String title;
- private AlertAction action;
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public AlertAction getAction() {
- return action;
- }
-
- public void setAction(AlertAction action) {
- this.action = action;
- }
-}
diff --git a/console/android/src/main/java/org/openremote/android/service/DeliveryStatus.java b/console/android/src/main/java/org/openremote/android/service/DeliveryStatus.java
deleted file mode 100644
index 68eb56162..000000000
--- a/console/android/src/main/java/org/openremote/android/service/DeliveryStatus.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.openremote.android.service;
-
-
-enum DeliveryStatus {
- /**
- * Not delivered to queue.
- */
- PENDING,
-
- /**
- * Delivered to queue for at least one device, device should soon pick it up.
- */
- QUEUED,
-
- /**
- * Picked up by receiving device and dismissed by user.
- */
- ACKNOWLEDGED
-}
diff --git a/console/android/src/main/java/org/openremote/android/service/OAuth2Service.java b/console/android/src/main/java/org/openremote/android/service/OAuth2Service.java
deleted file mode 100644
index 624944e97..000000000
--- a/console/android/src/main/java/org/openremote/android/service/OAuth2Service.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package org.openremote.android.service;
-
-import retrofit2.Call;
-import retrofit2.http.Field;
-import retrofit2.http.FormUrlEncoded;
-import retrofit2.http.POST;
-import retrofit2.http.Path;
-
-import java.util.Map;
-
-public interface OAuth2Service {
- @FormUrlEncoded
- @POST("/auth/realms/{realm}/protocol/openid-connect/token")
- Call<Map<String, String>> refreshToken(@Path("realm") String realm, @Field("grant_type") String grantType, @Field("client_id") String clientId, @Field("refresh_token") String refreshToken);
-
-}
diff --git a/console/android/src/main/java/org/openremote/android/service/RestApiResource.java b/console/android/src/main/java/org/openremote/android/service/RestApiResource.java
deleted file mode 100644
index 7c8b92e15..000000000
--- a/console/android/src/main/java/org/openremote/android/service/RestApiResource.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package org.openremote.android.service;
-
-
-import retrofit2.Call;
-import retrofit2.http.*;
-
-public interface RestApiResource {
- @FormUrlEncoded
- @PUT("/{realm}/notification/token")
- Call<Void> updateToken(@Path("realm") String realm, @Header("Authorization") String authorization, @Field("token") String token, @Field("device_id") String deviceId, @Field("device_type") String deviceType);
-
- @PUT("/{realm}/notification/{notificationId}/delivered")
- @Headers("Content-Type:application/json")
- Call<Void> notificationDelivered(@Path("realm") String realm, @Path("notificationId") Long notificationId, @Query("targetId") String targetId);
-
- @PUT("/{realm}/notification/{notificationId}/acknowledged")
- @Headers("Content-Type:application/json")
- Call<Void> notificationAcknowledged(@Path("realm") String realm, @Path("notificationId") Long notificationId, @Query("targetId") String targetId, @Body String acknowledgement);
-
-}
diff --git a/console/android/src/main/java/org/openremote/android/service/TokenCallback.java b/console/android/src/main/java/org/openremote/android/service/TokenCallback.java
deleted file mode 100644
index caeb3cd2f..000000000
--- a/console/android/src/main/java/org/openremote/android/service/TokenCallback.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.openremote.android.service;
-
-import java.io.IOException;
-
-public interface TokenCallback {
- void onToken(String accessToken) throws IOException;
-
- void onFailure(Throwable t);
-}
diff --git a/console/android/src/main/java/org/openremote/android/service/TokenService.java b/console/android/src/main/java/org/openremote/android/service/TokenService.java
deleted file mode 100644
index d8a08a846..000000000
--- a/console/android/src/main/java/org/openremote/android/service/TokenService.java
+++ /dev/null
@@ -1,251 +0,0 @@
-package org.openremote.android.service;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-import android.text.TextUtils;
-import okhttp3.MediaType;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
-import okhttp3.RequestBody;
-import org.openremote.android.R;
-import retrofit2.Call;
-import retrofit2.Callback;
-import retrofit2.Response;
-import retrofit2.Retrofit;
-import retrofit2.converter.jackson.JacksonConverterFactory;
-import retrofit2.converter.scalars.ScalarsConverterFactory;
-
-import javax.net.ssl.*;
-import java.io.IOException;
-import java.security.cert.CertificateException;
-import java.util.Locale;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-
-public class TokenService {
-
- private static final Logger LOG = Logger.getLogger(TokenService.class.getName());
-
- private final SharedPreferences sharedPref;
- private final String refreshTokenKey;
- private final String fcmTokenKey;
- private final String deviceIdKey;
- private final String realm;
- private final String baseUrl;
- private final OkHttpClient okHttpClient;
- private final OAuth2Service oauth2Service;
- private final RestApiResource restApiResource;
-
- public TokenService(Context context) {
- baseUrl = context.getString(R.string.OR_BASE_SERVER);
-
- Retrofit.Builder builder = new Retrofit.Builder()
- .baseUrl(baseUrl)
- .addConverterFactory(ScalarsConverterFactory.create())
- .addConverterFactory(JacksonConverterFactory.create());
-
- if (Boolean.parseBoolean(context.getString(R.string.SSL_IGNORE))) {
- okHttpClient = getUnsafeOkHttpClient();
- } else {
- okHttpClient = new OkHttpClient();
- }
-
- builder.client(okHttpClient);
- Retrofit retrofit = builder.build();
-
- oauth2Service = retrofit.create(OAuth2Service.class);
- restApiResource = retrofit.create(RestApiResource.class);
- sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
- refreshTokenKey = context.getString(R.string.SHARED_PREF_REFRESH_TOKEN);
- fcmTokenKey = context.getString(R.string.SHARED_PREF_FCM_TOKEN);
- deviceIdKey = context.getString(R.string.SHARED_PREF_DEVICE_ID);
- realm = context.getString(R.string.OR_REALM);
- }
-
- public void sendOrStoreFCMToken(String fcmToken, String deviceId) {
- LOG.info("Storing FCM token: " + fcmToken);
- LOG.info("Storing Device ID: " + deviceId);
- SharedPreferences.Editor editor = sharedPref.edit();
- editor.putString(fcmTokenKey, fcmToken);
- editor.putString(deviceIdKey, deviceId);
- editor.commit();
- }
-
- // TODO: Support other content types
- public void executeRequest(final String httpMethod, String url, String body) {
-
- // If relative URL assume it is relative to base URL
- if (!url.toLowerCase(Locale.ROOT).startsWith("http")) {
- if (url.startsWith("/")) {
- url = baseUrl + url;
- } else {
- url = baseUrl + "/" + url;
- }
- }
-
- // If URL is for our server and refresh token present then use authentication
- String refreshToken = sharedPref.getString(refreshTokenKey, null);
- boolean useAuth = url.startsWith(baseUrl) && !TextUtils.isEmpty(refreshToken);
- final Request.Builder requestBuilder = new Request.Builder().url(url);
- RequestBody requestBody = !TextUtils.isEmpty(body)
- ? RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)
- : null;
-
- try {
- switch (httpMethod.toUpperCase(Locale.ROOT)) {
- case "GET":
- requestBuilder.get();
- break;
- case "POST":
- requestBuilder.post(requestBody);
- break;
- case "PUT":
- requestBuilder.put(requestBody);
- break;
- case "PATCH":
- requestBuilder.patch(requestBody);
- break;
- case "DELETE":
- if (requestBody != null) {
- requestBuilder.delete(requestBody);
- } else {
- requestBuilder.delete();
- }
- break;
- default:
- throw new IllegalArgumentException("Unsupported HTTP Method: " + httpMethod);
- }
-
- LOG.info("Executing silent request: HTTP " + httpMethod + " " + url);
-
- if (useAuth) {
- withAccessToken(new TokenCallback() {
- @Override
- public void onToken(String accessToken) throws IOException {
- requestBuilder.addHeader("Authorization", accessToken);
- okHttpClient.newCall(requestBuilder.build()).execute();
- }
-
- @Override
- public void onFailure(Throwable t) {
- LOG.log(Level.SEVERE, "HTTP request failed", t);
- }
- });
- } else {
- okHttpClient.newCall(requestBuilder.build()).execute();
- }
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "HTTP request failed", e);
- }
- }
-
- public void notificationDelivered(final Long notificationId, final String fcmToken) {
- LOG.info("Notification status update 'delivered': " + notificationId);
-
- restApiResource.notificationDelivered(realm, notificationId, fcmToken).enqueue(new Callback<Void>() {
- @Override
- public void onResponse(Call<Void> call, Response<Void> response) {
- LOG.info("Notification status update success");
- }
-
- @Override
- public void onFailure(Call<Void> call, Throwable t) {
- LOG.log(Level.SEVERE, "Notification status update failed", t);
- }
- });
- }
-
- public void notificationAcknowledged(final Long notificationId, final String fcmToken, String acknowledgement) {
-
- LOG.info("Notification status update 'acknowledged' with value '" + acknowledgement + "': " + notificationId);
-
- if (TextUtils.isEmpty(acknowledgement)) {
- acknowledgement = "";
- }
-
- restApiResource.notificationAcknowledged(realm, notificationId, fcmToken, acknowledgement).enqueue(new Callback<Void>() {
- @Override
- public void onResponse(Call<Void> call, Response<Void> response) {
- LOG.info("Notification status update success");
- }
-
- @Override
- public void onFailure(Call<Void> call, Throwable t) {
- LOG.log(Level.SEVERE, "Notification status update failed", t);
- }
- });
- }
-
- static OkHttpClient getUnsafeOkHttpClient() {
- try {
- // Create a trust manager that does not validate certificate chains
- final TrustManager[] trustAllCerts = new TrustManager[]{
- new X509TrustManager() {
- @Override
- public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
- }
-
- @Override
- public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
- }
-
- @Override
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return new java.security.cert.X509Certificate[]{};
- }
- }
- };
-
- // Install the all-trusting trust manager
- final SSLContext sslContext = SSLContext.getInstance("SSL");
- sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
- // Create an ssl socket factory with our all-trusting manager
- final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
-
- OkHttpClient.Builder builder = new OkHttpClient.Builder();
- builder.sslSocketFactory(sslSocketFactory);
- builder.hostnameVerifier(new HostnameVerifier() {
- @Override
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- });
-
- OkHttpClient okHttpClient = builder.build();
- return okHttpClient;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- protected void withAccessToken(final TokenCallback callback) {
- Call<Map<String, String>> call = oauth2Service.refreshToken(realm, "refresh_token", "openremote", sharedPref.getString(refreshTokenKey, null));
- call.enqueue(new Callback<Map<String, String>>() {
- @Override
- public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
- if (response.isSuccessful()) {
- if (response.body() != null) {
- try {
- LOG.fine("Access token successfully updated");
- callback.onToken("Bearer " + response.body().get("access_token"));
- } catch (IOException e) {
- callback.onFailure(e);
- }
- } else {
- callback.onFailure(new NullPointerException("No response body on update access token request"));
- }
- } else {
- callback.onFailure(new IllegalStateException("Unsuccessful response in update access token request: " + response.code()));
- }
- }
-
- @Override
- public void onFailure(Call call, Throwable t) {
- callback.onFailure(t);
- }
- });
- }
-}
diff --git a/console/android/src/main/res/layout/error_layout.xml b/console/android/src/main/res/layout/error_layout.xml
deleted file mode 100644
index 95572bcdf..000000000
--- a/console/android/src/main/res/layout/error_layout.xml
+++ /dev/null
@@ -1,66 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/errorView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_alignParentEnd="true"
- android:layout_alignParentStart="true"
- android:background="@color/white"
- android:gravity="center"
- android:visibility="gone">
-
- <TextView
- android:id="@+id/errorTitle"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
-
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:text="@string/noConnectivity"/>
-
- <TextView
- android:id="@+id/errorExplanation"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/errorTitle"
- android:layout_centerHorizontal="true"
- android:layout_margin="20dp"
- android:gravity="center"
- android:text="@string/noConnectivityExplain"/>
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
-
- android:layout_below="@+id/errorExplanation"
- android:layout_centerHorizontal="true"
- android:orientation="vertical">
-
- <Button
- android:id="@+id/reload"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="reloadWebView"
- android:text="@string/retry"
- tools:text="retry"/>
-
- <Button
- android:id="@+id/exit"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="exitOnClick"
- android:text="@string/exit"
- tools:text="exit"/>
- </LinearLayout>
-
- <ImageView
- android:layout_width="48dp"
- android:layout_height="48dp"
- android:layout_above="@+id/errorTitle"
- android:layout_centerHorizontal="true"
- android:layout_marginBottom="16dp"
- android:src="@drawable/app_icon"/>
-
-
-</RelativeLayout>
\ No newline at end of file
diff --git a/console/android/src/main/res/menu/menu_shell.xml b/console/android/src/main/res/menu/menu_shell.xml
deleted file mode 100644
index 3e19a383b..000000000
--- a/console/android/src/main/res/menu/menu_shell.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- tools:context="org.openremote.android.ShellActivity">
-
-
-</menu>
diff --git a/console/android/src/main/res/values-w820dp/dimens.xml b/console/android/src/main/res/values-w820dp/dimens.xml
deleted file mode 100644
index 63fc81644..000000000
--- a/console/android/src/main/res/values-w820dp/dimens.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<resources>
- <!-- Example customization of dimensions originally defined in res/values/dimens.xml
- (such as screen margins) for screens with more than 820dp of available width. This
- would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
- <dimen name="activity_horizontal_margin">64dp</dimen>
-</resources>
diff --git a/console/android/src/main/res/values/color.xml b/console/android/src/main/res/values/color.xml
deleted file mode 100644
index db3011ac5..000000000
--- a/console/android/src/main/res/values/color.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources xmlns:tools="http://schemas.android.com/tools"
- tools:ignore="UnusedResources">
-
- <item name="black" type="color">#ff000000</item>
- <item name="white" type="color">#ffffffff</item>
-
- <item name="dark_grey" type="color">#ff455a64</item>
- <item name="medium_grey" type="color">#ff919194</item>
- <item name="light_grey" type="color">#ffcccccc</item>
- <item name="bright_grey" type="color">#fff5f5f5</item>
-
- <item name="dark_green" type="color">#ff006224</item>
- <item name="medium_green" type="color">#ff49a942</item>
- <item name="light_green" type="color">#ffc1d72f</item>
-
- <item name="red" type="color">#ffe64a19</item>
- <item name="yellow" type="color">#fffbc02d</item>
- <item name="blue" type="color">#ff1976d2</item>
- <item name="purple" type="color">#ff660092</item>
-
-</resources>
\ No newline at end of file
diff --git a/console/android/src/main/res/values/dimens.xml b/console/android/src/main/res/values/dimens.xml
deleted file mode 100644
index 47c822467..000000000
--- a/console/android/src/main/res/values/dimens.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<resources>
- <!-- Default screen margins, per the Android Design guidelines. -->
- <dimen name="activity_horizontal_margin">16dp</dimen>
- <dimen name="activity_vertical_margin">16dp</dimen>
-</resources>
diff --git a/console/android/src/main/res/values/strings.xml b/console/android/src/main/res/values/strings.xml
deleted file mode 100644
index 6411ab9ed..000000000
--- a/console/android/src/main/res/values/strings.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<resources>
- <string name="OR_CONSOLE_NAME">OpenRemote</string>
- <string name="OR_CONSOLE_PROVIDERS">geofence push storage</string>
- <string name="WEBSITE_URL">http://www.openremote.io/</string>
- <string name="OR_BASE_SERVER">http://192.168.0.143:8080</string>
- <string name="OR_CONSOLE_URL">/console/REALM/index.html</string>
- <string name="OR_CONSOLE_LOAD_ERROR_URL"></string>
- <string name="OR_CONSOLE_LOAD_TIMEOUT">5000</string>
- <string name="OR_CONSOLE_IGNORE_PAGE_ERRORS">false</string>
- <string name="SHARED_PREF_REFRESH_TOKEN">REFRESH_TOKEN</string>
- <string name="OR_REALM">REALM</string>
- <string name="SHARED_PREF_FCM_TOKEN">FCM_TOKEN_KEY</string>
- <string name="SHARED_PREF_DEVICE_ID">FCM_DEVICE_ID_KEY</string>
- <string name="retry">Try again</string>
- <string name="noConnectivity">Network connection not available.</string>
- <string name="noConnectivityExplain">Can\'t connect to service.</string>
- <string name="SHARED_PREF_OPENED_ALERT">OPENED_ALERT</string>
- <string name="AUTH_URL">/auth</string>
- <string name="SSL_IGNORE">false</string>
- <string name="exit">exit</string>
- <string name="fatalError">Sorry, there is a problem.</string>
- <string name="fatalErrorExplain">The service is not available, please try again later.</string>
- <string name="httpError">Invalid response from service.</string>
- <string name="httpErrorExplain">Can\'t connect to service.</string>
- <string name="downloading_file">Downloading File</string>
- <string name="downloading_enabled">Downloading enabled</string>
- <string name="error_downloading">Error downloading file</string>
- <string name="download_completed">Download completed</string>
-
-</resources>
diff --git a/console/android/src/main/res/values/styles.xml b/console/android/src/main/res/values/styles.xml
deleted file mode 100644
index f4bec3958..000000000
--- a/console/android/src/main/res/values/styles.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<resources>
-
- <style name="OpenRemoteTheme"
- parent="android:Theme.DeviceDefault.Light.NoActionBar">
- <item name="android:actionMenuTextColor">@color/dark_grey</item>
- </style>
-
-
-
- <style name="ConsoleView" parent="android:Theme.DeviceDefault.Light.NoActionBar">
- <item name="android:background">@color/white</item>
- </style>
-
-</resources>