Skip to content
Draft
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/gradle.lockfile

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import io.homeassistant.companion.android.BuildConfig
import io.homeassistant.companion.android.common.data.integration.DeviceRegistration
import io.homeassistant.companion.android.common.data.servers.ServerManager
import io.homeassistant.companion.android.onboarding.getMessagingToken
import io.homeassistant.companion.android.util.tryRegisterCurrentOrDefaultDistributor
import javax.inject.Inject
import kotlinx.coroutines.launch
import org.unifiedpush.android.connector.UnifiedPush
import timber.log.Timber

@ActivityScoped
Expand All @@ -21,11 +23,20 @@ class LaunchPresenterImpl @Inject constructor(
serverManager.defaultServers.forEach {
ioScope.launch {
try {
// Don't get a new push token if using UnifiedPush.
val messagingToken = if (!UnifiedPush.tryRegisterCurrentOrDefaultDistributor(view as Context)) {
getMessagingToken()
} else {
null
}
serverManager.integrationRepository(it.id).updateRegistration(
DeviceRegistration(
"${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
null,
getMessagingToken()
appVersion = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
deviceName = null,
pushToken = messagingToken,
// A blank url indicates to use the build-time push url.
pushUrl = messagingToken?.let { "" },
pushEncrypt = messagingToken == null && UnifiedPush.getAckDistributor(view as Context) != null
)
)
serverManager.integrationRepository(it.id).getConfig() // Update cached data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ class FirebaseCloudMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
mainScope.launch {
Timber.d("Refreshed token: $token")
if (messagingManager.isUnifiedPushEnabled()) {
// Updating registration while using UnifiedPush will overwrite its token, so ignore new FCM tokens.
Timber.d("Not trying to update registration since UnifiedPush is being used.")
return@launch
}
if (!serverManager.isRegistered()) {
Timber.d("Not trying to update registration since we aren't authenticated.")
return@launch
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,18 @@
android:value="true" />
</service>

<receiver
android:name=".unifiedpush.UnifiedPushReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="org.unifiedpush.android.connector.MESSAGE"/>
<action android:name="org.unifiedpush.android.connector.UNREGISTERED"/>
<action android:name="org.unifiedpush.android.connector.NEW_ENDPOINT"/>
<action android:name="org.unifiedpush.android.connector.REGISTRATION_FAILED"/>
</intent-filter>
</receiver>

<receiver
android:name=".notifications.NotificationActionReceiver"
android:enabled="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import dagger.hilt.android.AndroidEntryPoint
import io.homeassistant.companion.android.BuildConfig
import io.homeassistant.companion.android.common.R as commonR
import io.homeassistant.companion.android.common.data.integration.DeviceRegistration
import io.homeassistant.companion.android.common.data.prefs.PrefsRepository
import io.homeassistant.companion.android.common.data.servers.ServerManager
import io.homeassistant.companion.android.database.sensor.SensorDao
import io.homeassistant.companion.android.database.server.Server
Expand All @@ -31,6 +32,7 @@ import io.homeassistant.companion.android.settings.SettingViewModel
import io.homeassistant.companion.android.settings.server.ServerChooserFragment
import io.homeassistant.companion.android.util.UrlUtil
import io.homeassistant.companion.android.util.compose.HomeAssistantAppTheme
import io.homeassistant.companion.android.util.tryRegisterCurrentOrDefaultDistributor
import io.homeassistant.companion.android.webview.WebViewActivity
import javax.inject.Inject
import javax.net.ssl.SSLException
Expand All @@ -39,6 +41,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.unifiedpush.android.connector.UnifiedPush
import retrofit2.HttpException
import timber.log.Timber

Expand All @@ -54,6 +57,9 @@ class LaunchActivity : AppCompatActivity(), LaunchView {
@Inject
lateinit var sensorDao: SensorDao

@Inject
lateinit var prefsRepository: PrefsRepository

private val mainScope = CoroutineScope(Dispatchers.Main + Job())

private val settingViewModel: SettingViewModel by viewModels()
Expand Down Expand Up @@ -138,8 +144,13 @@ class LaunchActivity : AppCompatActivity(), LaunchView {
mainScope.launch {
if (result != null) {
val (url, authCode, deviceName, deviceTrackingEnabled, notificationsEnabled) = result
val messagingToken = getMessagingToken()
if (messagingToken.isBlank() && BuildConfig.FLAVOR == "full") {
// Try UnifiedPush first, then fallback to FCM token.
val messagingToken = if (!UnifiedPush.tryRegisterCurrentOrDefaultDistributor(this@LaunchActivity)) {
getMessagingToken()
} else {
null
}
if (messagingToken != null && messagingToken.isBlank() && BuildConfig.FLAVOR == "full") {
AlertDialog.Builder(this@LaunchActivity)
.setTitle(commonR.string.firebase_error_title)
.setMessage(commonR.string.firebase_error_message)
Expand Down Expand Up @@ -176,7 +187,7 @@ class LaunchActivity : AppCompatActivity(), LaunchView {
url: String,
authCode: String,
deviceName: String,
messagingToken: String,
messagingToken: String?,
deviceTrackingEnabled: Boolean,
notificationsEnabled: Boolean
) {
Expand All @@ -196,12 +207,16 @@ class LaunchActivity : AppCompatActivity(), LaunchView {
serverManager.authenticationRepository(serverId).registerAuthorizationCode(authCode)
serverManager.integrationRepository(serverId).registerDevice(
DeviceRegistration(
"${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
deviceName,
messagingToken
appVersion = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
deviceName = deviceName,
pushToken = messagingToken,
// A blank url indicates to use the build-time push url.
pushUrl = messagingToken?.let { "" },
pushEncrypt = messagingToken == null && !UnifiedPush.getAckDistributor(this.applicationContext).isNullOrBlank()
)
)
serverId = serverManager.convertTemporaryServer(serverId)
prefsRepository.setUnifiedPushEnabled(messagingToken == null)
} catch (e: Exception) {
// Fatal errors: if one of these calls fail, the app cannot proceed.
// Show an error, clean up the session and require new registration.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

abstract class LaunchPresenterBase(
private val view: LaunchView,
internal val view: LaunchView,
internal val serverManager: ServerManager
) : LaunchPresenter {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,50 @@ class MessagingManager @Inject constructor(

private val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job())

suspend fun isUnifiedPushEnabled(): Boolean =
prefsRepository.isUnifiedPushEnabled()

suspend fun setUnifiedPushEnabled(enabled: Boolean) =
prefsRepository.setUnifiedPushEnabled(enabled)

fun handleMessage(notificationData: Map<String, Any>, source: String, serverId: Int = ServerManager.SERVER_ID_ACTIVE) {
val flattened = mutableMapOf<String, String>()
if (notificationData.containsKey("data")) {
for ((key, value) in notificationData["data"] as Map<*, *>) {
if (key == "actions" && value is List<*>) {
value.forEachIndexed { i, action ->
if (action is Map<*, *>) {
flattened["action_${i + 1}_key"] = action["action"].toString()
flattened["action_${i + 1}_title"] = action["title"].toString()
action["uri"]?.let { uri -> flattened["action_${i + 1}_uri"] = uri.toString() }
action["behavior"]?.let { behavior -> flattened["action_${i + 1}_behavior"] = behavior.toString() }
}
}
} else {
flattened[key.toString()] = value.toString()
}
}
}
// Message and title are in the root unlike all the others.
listOf("message", "title").forEach { key ->
if (notificationData.containsKey(key)) {
flattened[key] = notificationData[key].toString()
}
}
if (notificationData.containsKey("registration_info")) {
val registrationInfo = notificationData["registration_info"]
if (registrationInfo is Map<*, *> && registrationInfo.containsKey("webhook_id")) {
flattened["webhook_id"] = registrationInfo["webhook_id"].toString()
}
}
if (!flattened.containsKey("webhook_id")) {
serverManager.getServer(serverId)?.let { server ->
flattened["webhook_id"] = server.connection.webhookId.toString()
}
}
handleMessage(flattened, source)
}

fun handleMessage(notificationData: Map<String, String>, source: String) {
var now = System.currentTimeMillis()
var jsonData = notificationData
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import io.homeassistant.companion.android.settings.vehicle.ManageAndroidAutoSett
import io.homeassistant.companion.android.settings.wear.SettingsWearActivity
import io.homeassistant.companion.android.settings.wear.SettingsWearDetection
import io.homeassistant.companion.android.settings.widgets.ManageWidgetsSettingsFragment
import io.homeassistant.companion.android.unifiedpush.UnifiedPushManager
import io.homeassistant.companion.android.webview.WebViewActivity
import java.time.Instant
import java.time.ZoneId
Expand Down Expand Up @@ -229,6 +230,7 @@ class SettingsFragment(
}

updateNotificationChannelPrefs()
updateNotificationUnifiedPushPrefs()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
findPreference<Preference>("notification_permission")?.let {
Expand Down Expand Up @@ -480,6 +482,30 @@ class SettingsFragment(
}
}

private fun updateNotificationUnifiedPushPrefs() {
val notificationsEnabled =
Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
NotificationManagerCompat.from(requireContext()).areNotificationsEnabled()

findPreference<ListPreference>("notification_unifiedpush")?.let {
val distributors = presenter.getUnifiedPushDistributors()
it.isVisible = notificationsEnabled && distributors.isNotEmpty()
val pm = requireContext().packageManager
it.entries = distributors.map { distributor ->
// Map package name to app display name.
try {
pm.getApplicationLabel(pm.getApplicationInfo(distributor, PackageManager.GET_META_DATA)).toString()
} catch (_: PackageManager.NameNotFoundException) {
distributor
}
}.toTypedArray() + getString(commonR.string.disabled)
it.entryValues = distributors.toTypedArray() + UnifiedPushManager.DISTRIBUTOR_DISABLED
if (it.value == null) {
it.value = UnifiedPushManager.DISTRIBUTOR_DISABLED
}
}
}

private fun onServerLockResult(result: Int): Boolean {
if (result == Authenticator.SUCCESS && serverAuth != null) {
(activity as? SettingsActivity)?.setAppActive(serverAuth, true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ interface SettingsPresenter {
fun getServersFlow(): StateFlow<List<Server>>
fun getServerCount(): Int
suspend fun getNotificationRateLimits(): RateLimitResponse?
fun getUnifiedPushDistributors(): List<String>
fun showChangeLog(context: Context)
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import io.homeassistant.companion.android.onboarding.getMessagingToken
import io.homeassistant.companion.android.sensors.LocationSensorManager
import io.homeassistant.companion.android.settings.language.LanguagesManager
import io.homeassistant.companion.android.themes.ThemesManager
import io.homeassistant.companion.android.unifiedpush.UnifiedPushManager
import io.homeassistant.companion.android.util.ChangeLog
import io.homeassistant.companion.android.util.UrlUtil
import javax.inject.Inject
Expand All @@ -50,6 +51,7 @@ class SettingsPresenterImpl @Inject constructor(
private val prefsRepository: PrefsRepository,
private val themesManager: ThemesManager,
private val langsManager: LanguagesManager,
private val unifiedPushManager: UnifiedPushManager,
private val changeLog: ChangeLog,
private val settingsDao: SettingsDao,
private val sensorDao: SensorDao
Expand Down Expand Up @@ -108,6 +110,7 @@ class SettingsPresenterImpl @Inject constructor(
"languages" -> langsManager.getCurrentLang()
"page_zoom" -> prefsRepository.getPageZoomLevel().toString()
"screen_orientation" -> prefsRepository.getScreenOrientation()
"notification_unifiedpush" -> unifiedPushManager.getDistributor()
else -> throw IllegalArgumentException("No string found by this key: $key")
}
}
Expand All @@ -119,6 +122,7 @@ class SettingsPresenterImpl @Inject constructor(
"languages" -> langsManager.saveLang(value)
"page_zoom" -> prefsRepository.setPageZoomLevel(value?.toIntOrNull())
"screen_orientation" -> prefsRepository.saveScreenOrientation(value)
"notification_unifiedpush" -> unifiedPushManager.saveDistributor(value)
else -> throw IllegalArgumentException("No string found by this key: $key")
}
}
Expand Down Expand Up @@ -155,6 +159,9 @@ class SettingsPresenterImpl @Inject constructor(
}
}

override fun getUnifiedPushDistributors(): List<String> =
unifiedPushManager.getDistributors()

override fun showChangeLog(context: Context) {
changeLog.showChangeLog(context, true)
}
Expand Down
Loading