Bump org.jlleitschuh.gradle.ktlint from 11.1.0 to 11.2.0 (#3334)

* Bump org.jlleitschuh.gradle.ktlint from 11.1.0 to 11.2.0

Bumps org.jlleitschuh.gradle.ktlint from 11.1.0 to 11.2.0.

---
updated-dependencies:
- dependency-name: org.jlleitschuh.gradle.ktlint
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* gradlew ktlintFormat

* Rename packages with underscores

> Task :app:ktlintMainSourceSetFormat FAILED
home-assistant-android\app\src\main\java\io\homeassistant\companion\android\widgets\media_player_controls\MediaPlayerControlsWidget.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)
home-assistant-android\app\src\main\java\io\homeassistant\companion\android\widgets\media_player_controls\MediaPlayerControlsWidgetConfigureActivity.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)

Rename: media_player_controls to mediaplayer

> Task :wear:ktlintMainSourceSetFormat FAILED
home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupActivity.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)
home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupModule.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)
home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupPresenter.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)
home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupPresenterImpl.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)
home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupView.kt:1:1 Package name must not contain underscore (cannot be auto-corrected)

Rename: manual_setup to manual

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Joris Pelgröm <joris.pelgrom@gmail.com>
This commit is contained in:
dependabot[bot] 2023-03-01 12:05:54 -05:00 committed by GitHub
parent 0c4c32e512
commit a2f85ef475
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
215 changed files with 1609 additions and 914 deletions

View file

@ -23,8 +23,9 @@ private const val FATAL_CRASH_FILE = "/fatalcrash/last_crash"
fun initCrashReporting(context: Context, enabled: Boolean) {
// Don't init on debug builds or when disabled
if (!shouldEnableCrashHandling(enabled))
if (!shouldEnableCrashHandling(enabled)) {
return
}
SentryAndroid.init(context) { options ->
options.isEnableAutoSessionTracking = true
@ -66,8 +67,9 @@ fun initCrashReporting(context: Context, enabled: Boolean) {
}
suspend fun getLatestFatalCrash(context: Context, enabled: Boolean): String? = withContext(Dispatchers.IO) {
if (!shouldEnableCrashHandling(enabled))
if (!shouldEnableCrashHandling(enabled)) {
return@withContext null
}
var toReturn: String? = null
try {

View file

@ -51,7 +51,6 @@ class HighAccuracyLocationService : Service() {
@Synchronized
fun stopService(context: Context) {
Log.d(TAG, "Try stopping high accuracy location service...")
LAUNCHER.stopService(context)
}

View file

@ -74,8 +74,11 @@ class MatterCommissioningViewModel @Inject constructor(
val coreSupport = matterManager.coreSupportsCommissioning(id)
step =
if (coreSupport) CommissioningFlowStep.Confirmation
else CommissioningFlowStep.NotSupported
if (coreSupport) {
CommissioningFlowStep.Confirmation
} else {
CommissioningFlowStep.NotSupported
}
}
}
@ -101,8 +104,11 @@ class MatterCommissioningViewModel @Inject constructor(
val result = matterManager.commissionDevice(code, serverId)
step =
if (result?.success == true) CommissioningFlowStep.Success
else CommissioningFlowStep.Failure(result?.errorCode)
if (result?.success == true) {
CommissioningFlowStep.Success
} else {
CommissioningFlowStep.Failure(result?.errorCode)
}
}
}
}

View file

@ -64,7 +64,6 @@ class ActivitySensorManager : BroadcastReceiver(), SensorManager {
}
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
ACTION_UPDATE_ACTIVITY -> handleActivityUpdate(intent, context)
ACTION_SLEEP_ACTIVITY -> handleSleepUpdate(intent, context)
@ -100,8 +99,9 @@ class ActivitySensorManager : BroadcastReceiver(), SensorManager {
val result = ActivityRecognitionResult.extractResult(intent)
var probActivity = result?.let { typeToString(it.mostProbableActivity) }
if (probActivity == "on_foot")
if (probActivity == "on_foot") {
probActivity = result?.let { getSubActivity(it) }
}
if (probActivity != null && result != null) {
onSensorUpdated(
@ -274,7 +274,6 @@ class ActivitySensorManager : BroadcastReceiver(), SensorManager {
}
private fun getSensorIcon(activity: String): String {
return when (activity) {
"in_vehicle" -> "mdi:car"
"on_bicycle" -> "mdi:bike"

View file

@ -31,10 +31,11 @@ class AndroidAutoSensorManager : SensorManager, Observer<Int> {
get() = commonR.string.sensor_name_android_auto
override suspend fun getAvailableSensors(context: Context): List<SensorManager.BasicSensor> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
listOf(androidAutoConnected)
else
} else {
emptyList()
}
}
override fun requiredPermissions(sensorId: String): Array<String> {
@ -85,7 +86,7 @@ class AndroidAutoSensorManager : SensorManager, Observer<Int> {
androidAutoConnected.statelessIcon,
mapOf(
"connection_type" to typeString
),
)
)
}
}

View file

@ -199,8 +199,11 @@ class LocationSensorManager : LocationSensorManagerBase() {
when (command) {
DeviceCommandData.TURN_ON, DeviceCommandData.TURN_OFF, MessagingManager.FORCE_ON -> {
var turnOn = command != DeviceCommandData.TURN_OFF
if (turnOn) Log.d(TAG, "Forcing of high accuracy mode enabled")
else Log.d(TAG, "Forcing of high accuracy mode disabled")
if (turnOn) {
Log.d(TAG, "Forcing of high accuracy mode enabled")
} else {
Log.d(TAG, "Forcing of high accuracy mode disabled")
}
forceHighAccuracyModeOn = turnOn
forceHighAccuracyModeOff = false
setHighAccuracyModeSetting(latestContext, turnOn)
@ -219,8 +222,9 @@ class LocationSensorManager : LocationSensorManagerBase() {
}
MessagingManager.HIGH_ACCURACY_SET_UPDATE_INTERVAL -> {
if (lastHighAccuracyMode)
if (lastHighAccuracyMode) {
restartHighAccuracyService(getHighAccuracyModeIntervalSetting(latestContext))
}
}
}
}
@ -311,7 +315,6 @@ class LocationSensorManager : LocationSensorManagerBase() {
if (highAccuracyModeEnabled != lastHighAccuracyMode ||
updateIntervalHighAccuracySeconds != lastHighAccuracyUpdateInterval
) {
if (highAccuracyModeEnabled) {
Log.d(TAG, "High accuracy mode parameters changed. Enable high accuracy mode.")
if (updateIntervalHighAccuracySeconds != lastHighAccuracyUpdateInterval) {
@ -416,7 +419,6 @@ class LocationSensorManager : LocationSensorManagerBase() {
}
private fun getHighAccuracyModeState(): Boolean {
var highAccuracyMode = getHighAccuracyModeSetting()
if (!highAccuracyMode) return false
@ -447,7 +449,6 @@ class LocationSensorManager : LocationSensorManagerBase() {
}
private fun shouldEnableHighAccuracyMode(): Boolean {
val highAccuracyModeBTDevicesSetting = getSetting(
latestContext,
backgroundLocation,
@ -485,8 +486,9 @@ class LocationSensorManager : LocationSensorManagerBase() {
if (foundDevices.isNotEmpty()) {
highAccuracyModeBTDevices.remove(it)
foundDevices.forEach { btDevice ->
if (!highAccuracyModeBTDevices.contains(btDevice.address))
if (!highAccuracyModeBTDevices.contains(btDevice.address)) {
highAccuracyModeBTDevices.add(btDevice.address)
}
}
updatedBtDeviceNames = true
}
@ -506,8 +508,11 @@ class LocationSensorManager : LocationSensorManagerBase() {
btDevConnected = bluetoothDevices.any { it.connected && highAccuracyModeBTDevices.contains(it.address) }
if (!forceHighAccuracyModeOn && !forceHighAccuracyModeOff) {
if (!btDevConnected) Log.d(TAG, "High accuracy mode disabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) not connected (Connected devices: $bluetoothDevices)")
else Log.d(TAG, "High accuracy mode enabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) connected (Connected devices: $bluetoothDevices)")
if (!btDevConnected) {
Log.d(TAG, "High accuracy mode disabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) not connected (Connected devices: $bluetoothDevices)")
} else {
Log.d(TAG, "High accuracy mode enabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) connected (Connected devices: $bluetoothDevices)")
}
}
}
@ -524,8 +529,11 @@ class LocationSensorManager : LocationSensorManagerBase() {
inZone = zoneExpEntered || zoneExited
if (!forceHighAccuracyModeOn && !forceHighAccuracyModeOff) {
if (!inZone) Log.d(TAG, "High accuracy mode disabled, because not in zone $highAccuracyExpZones")
else Log.d(TAG, "High accuracy mode enabled, because in zone $highAccuracyExpZones")
if (!inZone) {
Log.d(TAG, "High accuracy mode disabled, because not in zone $highAccuracyExpZones")
} else {
Log.d(TAG, "High accuracy mode enabled, because in zone $highAccuracyExpZones")
}
}
}
@ -572,11 +580,14 @@ class LocationSensorManager : LocationSensorManagerBase() {
settingName = SETTING_SEND_LOCATION_AS,
settingType = SensorSettingType.LIST,
entries = listOf(
SEND_LOCATION_AS_EXACT, SEND_LOCATION_AS_ZONE_ONLY
SEND_LOCATION_AS_EXACT,
SEND_LOCATION_AS_ZONE_ONLY
),
default = SEND_LOCATION_AS_EXACT
)
} else SEND_LOCATION_AS_EXACT
} else {
SEND_LOCATION_AS_EXACT
}
}
private fun removeAllLocationUpdateRequests() {
@ -590,7 +601,9 @@ class LocationSensorManager : LocationSensorManagerBase() {
Log.d(TAG, "Removing background location requests.")
val backgroundIntent = getLocationUpdateIntent(false)
fusedLocationProviderClient?.removeLocationUpdates(backgroundIntent)
} else Log.d(TAG, "Cannot remove background location requests. Location provider is not set.")
} else {
Log.d(TAG, "Cannot remove background location requests. Location provider is not set.")
}
}
private fun removeGeofenceUpdateRequests() {
@ -601,7 +614,9 @@ class LocationSensorManager : LocationSensorManagerBase() {
geofenceRegistered.clear()
lastEnteredGeoZones.clear()
lastExitedGeoZones.clear()
} else Log.d(TAG, "Cannot remove geofence location requests. Geofence provider is not set.")
} else {
Log.d(TAG, "Cannot remove geofence location requests. Geofence provider is not set.")
}
}
private fun requestLocationUpdates() {
@ -1148,8 +1163,9 @@ class LocationSensorManager : LocationSensorManagerBase() {
context: Context
) {
latestContext = context
if (isEnabled(context, zoneLocation) || isEnabled(context, backgroundLocation))
if (isEnabled(context, zoneLocation) || isEnabled(context, backgroundLocation)) {
setupLocationTracking()
}
val sensorDao = AppDatabase.getInstance(latestContext).sensorDao()
val sensorSetting = sensorDao.getSettings(singleAccurateLocation.id)
val includeSensorUpdate = sensorSetting.firstOrNull { it.name == SETTING_INCLUDE_SENSOR_UPDATE }?.value ?: "false"
@ -1161,7 +1177,8 @@ class LocationSensorManager : LocationSensorManagerBase() {
}
)
}
} else
} else {
sensorDao.add(SensorSetting(singleAccurateLocation.id, SETTING_INCLUDE_SENSOR_UPDATE, "false", SensorSettingType.TOGGLE))
}
}
}

View file

@ -115,7 +115,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC
}
private suspend fun findWearDevicesWithApp() {
try {
val capabilityInfo = capabilityClient
.getCapability(CAPABILITY_WEAR_APP, CapabilityClient.FILTER_ALL)
@ -135,7 +134,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC
}
private suspend fun findAllWearDevices() {
try {
val connectedNodes = nodeClient.connectedNodes.await()
@ -151,7 +149,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC
}
private fun updateUI() {
val wearNodesWithApp = wearNodesWithApp
val allConnectedNodes = allConnectedNodes
@ -185,7 +182,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC
}
private fun openPlayStoreOnWearDevicesWithoutApp() {
val wearNodesWithApp = wearNodesWithApp ?: return
val allConnectedNodes = allConnectedNodes ?: return

View file

@ -22,7 +22,7 @@ object SettingsWearDetection {
} catch (e: Exception) {
if (e is ApiException && e.statusCode == CommonStatusCodes.API_NOT_CONNECTED && e.message?.contains("API_UNAVAILABLE") == true) {
// Wearable.API is not available on this device.
Log.d(TAG, "API unavailable for discovering nodes (no Wear)",)
Log.d(TAG, "API unavailable for discovering nodes (no Wear)")
} else {
Log.e(TAG, "Exception while discovering nodes", e)
}

View file

@ -125,8 +125,11 @@ class SettingsWearViewModel @Inject constructor(
Log.e(TAG, "Exception while rendering template", e)
// JsonMappingException suggests that template is not a String (= error)
templateTileContentRendered.value = getApplication<Application>().getString(
if (e.cause is JsonMappingException) commonR.string.template_error
else commonR.string.template_render_error
if (e.cause is JsonMappingException) {
commonR.string.template_error
} else {
commonR.string.template_render_error
}
)
}
}
@ -136,10 +139,11 @@ class SettingsWearViewModel @Inject constructor(
}
fun onEntitySelected(checked: Boolean, entityId: String) {
if (checked)
if (checked) {
favoriteEntityIds.add(entityId)
else
} else {
favoriteEntityIds.remove(entityId)
}
sendHomeFavorites(favoriteEntityIds.toList())
}

View file

@ -79,7 +79,8 @@ class SettingsWearMainView : AppCompatActivity() {
if (result != null) {
val (url, authCode, deviceName, deviceTrackingEnabled, _) = result
settingsWearViewModel.sendAuthToWear(url, authCode, deviceName, deviceTrackingEnabled, true)
} else
} else {
Log.e(TAG, "onOnboardingComplete: Activity result returned null intent data")
}
}
}

View file

@ -33,7 +33,7 @@ class EntityGridVehicleScreen(
carContext: CarContext,
val integrationRepository: IntegrationRepository,
val title: String,
val entitiesFlow: Flow<List<Entity<*>>>,
val entitiesFlow: Flow<List<Entity<*>>>
) : Screen(carContext) {
companion object {

View file

@ -86,7 +86,9 @@ class HaCarAppService : CarAppService() {
serverManager.integrationRepository(id).getEntities()
?.associate { it.entityId to it }
?.toMutableMap()
} else null
} else {
null
}
if (entities != null) {
allEntities.emit(entities.toImmutableMap())
serverManager.integrationRepository(id).getEntityUpdates()?.collect { entity ->

View file

@ -58,7 +58,7 @@ class MainVehicleScreen(
"lock" to commonR.string.locks,
"scene" to commonR.string.scenes,
"script" to commonR.string.scripts,
"switch" to commonR.string.switches,
"switch" to commonR.string.switches
)
private val SUPPORTED_DOMAINS = SUPPORTED_DOMAINS_WITH_STRING.keys
@ -66,7 +66,7 @@ class MainVehicleScreen(
"device_tracker",
"person",
"sensor",
"zone",
"zone"
)
}

View file

@ -34,7 +34,7 @@ import io.homeassistant.companion.android.common.R as commonR
class MapVehicleScreen(
carContext: CarContext,
val integrationRepository: IntegrationRepository,
val entitiesFlow: Flow<List<Entity<*>>>,
val entitiesFlow: Flow<List<Entity<*>>>
) : Screen(carContext) {
companion object {

View file

@ -142,7 +142,7 @@
android:resource="@xml/entity_widget_info" />
</receiver>
<receiver android:name=".widgets.media_player_controls.MediaPlayerControlsWidget" android:label="@string/widget_media_player_description"
<receiver android:name=".widgets.mediaplayer.MediaPlayerControlsWidget" android:label="@string/widget_media_player_description"
android:exported="false">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
@ -205,7 +205,7 @@
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<activity android:name=".widgets.media_player_controls.MediaPlayerControlsWidgetConfigureActivity"
<activity android:name=".widgets.mediaplayer.MediaPlayerControlsWidgetConfigureActivity"
android:configChanges="orientation|screenSize"
android:exported="true">
<intent-filter>

View file

@ -22,7 +22,7 @@ import io.homeassistant.companion.android.util.LifecycleHandler
import io.homeassistant.companion.android.websocket.WebsocketBroadcastReceiver
import io.homeassistant.companion.android.widgets.button.ButtonWidget
import io.homeassistant.companion.android.widgets.entity.EntityWidget
import io.homeassistant.companion.android.widgets.media_player_controls.MediaPlayerControlsWidget
import io.homeassistant.companion.android.widgets.mediaplayer.MediaPlayerControlsWidget
import io.homeassistant.companion.android.widgets.template.TemplateWidget
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@ -213,11 +213,12 @@ open class HomeAssistantApplication : Application() {
// Register for faster sensor updates if enabled
val settingDao = AppDatabase.getInstance(applicationContext).settingsDao().get(0)
if (settingDao != null && (settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_WHILE_CHARGING || settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_ALWAYS))
if (settingDao != null && (settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_WHILE_CHARGING || settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_ALWAYS)) {
registerReceiver(
sensorReceiver,
IntentFilter(Intent.ACTION_TIME_TICK)
)
}
// Update widgets when the screen turns on, updates are skipped if widgets were not added
val buttonWidget = ButtonWidget()

View file

@ -18,15 +18,17 @@ class Authenticator(context: Context, fragmentActivity: FragmentActivity, callba
private val executor = ContextCompat.getMainExecutor(context)
private val biometricPrompt = BiometricPrompt(
fragmentActivity, executor,
fragmentActivity,
executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
Log.d("Unlock", "onAuthenticationError -> $errorCode :: $errString")
if (errorCode == BiometricPrompt.ERROR_USER_CANCELED)
if (errorCode == BiometricPrompt.ERROR_USER_CANCELED) {
callback(CANCELED)
else
} else {
callback(ERROR)
}
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()

View file

@ -46,7 +46,9 @@ object CameraControl : HaControl {
val image = if (baseUrl != null && (entity.attributes["entity_picture"] as? String)?.isNotBlank() == true) {
getThumbnail(baseUrl + entity.attributes["entity_picture"] as String)
} else null
} else {
null
}
val icon = if (image != null) {
Icon.createWithBitmap(image)
} else {

View file

@ -58,10 +58,12 @@ object ClimateControl : HaControl {
entity.attributes["current_temperature"] as? Number
)?.toFloat() ?: 0f
// Ensure the current value is never lower than the minimum or higher than the maximum
if (currentValue < minValue)
if (currentValue < minValue) {
currentValue = minValue
if (currentValue > maxValue)
}
if (currentValue > maxValue) {
currentValue = maxValue
}
val temperatureUnit = entity.attributes["temperature_unit"] ?: ""
val temperatureStepSize = (entity.attributes["target_temperature_step"] as? Number)?.toFloat()
@ -100,10 +102,11 @@ object ClimateControl : HaControl {
}
override fun getDeviceType(entity: Entity<Map<String, Any>>): Int =
if (entityShouldBePresentedAsThermostat(entity))
if (entityShouldBePresentedAsThermostat(entity)) {
DeviceTypes.TYPE_THERMOSTAT
else
} else {
DeviceTypes.TYPE_AC_HEATER
}
override fun getDomainString(context: Context, entity: Entity<Map<String, Any>>): String =
context.getString(commonR.string.domain_climate)

View file

@ -40,7 +40,7 @@ object CoverControl : HaControl {
)
val position = entity.getCoverPosition()
control.setControlTemplate(
if ((entity.attributes["supported_features"] as Int) and SUPPORT_SET_POSITION == SUPPORT_SET_POSITION)
if ((entity.attributes["supported_features"] as Int) and SUPPORT_SET_POSITION == SUPPORT_SET_POSITION) {
ToggleRangeTemplate(
entity.entityId,
entity.state in listOf("open", "opening"),
@ -54,7 +54,7 @@ object CoverControl : HaControl {
"%.0f%%"
)
)
else
} else {
ToggleTemplate(
entity.entityId,
ControlButton(
@ -62,6 +62,7 @@ object CoverControl : HaControl {
"Description"
)
)
}
)
return control
}

View file

@ -247,8 +247,11 @@ class HaControlsProviderService : ControlsProviderService() {
if (serverManager.getServer(serverId) == null) {
controlIds.forEach {
val entityId =
if (it.split(".")[0].toIntOrNull() != null) it.removePrefix("$serverId.")
else it
if (it.split(".")[0].toIntOrNull() != null) {
it.removePrefix("$serverId.")
} else {
it
}
val entity = getFailedEntity(entityId, Exception())
domainToHaControl["ha_failed"]?.createControl(
applicationContext,
@ -257,7 +260,7 @@ class HaControlsProviderService : ControlsProviderService() {
systemId = it,
entityId = entityId,
serverId = serverId,
area = getAreaForEntity(entity.entityId, serverId),
area = getAreaForEntity(entity.entityId, serverId)
)
)?.let { control -> subscriber.onNext(control) }
}
@ -269,8 +272,11 @@ class HaControlsProviderService : ControlsProviderService() {
val getDeviceRegistry = ioScope.async { serverManager.webSocketRepository(serverId).getDeviceRegistry() }
val getEntityRegistry = ioScope.async { serverManager.webSocketRepository(serverId).getEntityRegistry() }
val entityIds = controlIds.map {
if (it.split(".")[0].toIntOrNull() != null) it.removePrefix("$serverId.")
else it
if (it.split(".")[0].toIntOrNull() != null) {
it.removePrefix("$serverId.")
} else {
it
}
}
val entities = mutableMapOf<String, Entity<Map<String, Any>>>()
val baseUrl = serverManager.getServer(serverId)?.connection?.getUrl()?.toString()?.removeSuffix("/") ?: ""
@ -386,8 +392,9 @@ class HaControlsProviderService : ControlsProviderService() {
baseUrl = baseUrl
)
)
if (control != null)
if (control != null) {
subscriber.onNext(control)
}
}
}
}
@ -422,8 +429,11 @@ class HaControlsProviderService : ControlsProviderService() {
baseUrl: String
) {
val entityIds = controlIds.map {
if (it.split(".")[0].toIntOrNull() != null) it.removePrefix("$serverId.")
else it
if (it.split(".")[0].toIntOrNull() != null) {
it.removePrefix("$serverId.")
} else {
it
}
}
entities.forEach {
coroutineScope.launch {
@ -449,8 +459,9 @@ class HaControlsProviderService : ControlsProviderService() {
info
)
}
if (control != null)
if (control != null) {
subscriber.onNext(control)
}
}
}
}
@ -485,6 +496,8 @@ class HaControlsProviderService : ControlsProviderService() {
} else {
setting == ControlsAuthRequiredSetting.ALL
}
} else false
} else {
false
}
}
}

View file

@ -30,7 +30,7 @@ object LightControl : HaControl {
): Control.StatefulBuilder {
val position = entity.getLightBrightness()
control.setControlTemplate(
if (entity.supportsLightBrightness())
if (entity.supportsLightBrightness()) {
ToggleRangeTemplate(
entity.entityId,
entity.state == "on",
@ -44,7 +44,7 @@ object LightControl : HaControl {
"%.0f%%"
)
)
else
} else {
ToggleTemplate(
entity.entityId,
ControlButton(
@ -52,6 +52,7 @@ object LightControl : HaControl {
"Description"
)
)
}
)
return control
}

View file

@ -45,10 +45,11 @@ object VacuumControl : HaControl {
ToggleTemplate(
entity.entityId,
ControlButton(
if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON)
if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON) {
entity.state == "on"
else
entity.state == "cleaning",
} else {
entity.state == "cleaning"
},
"Description"
)
)
@ -68,9 +69,9 @@ object VacuumControl : HaControl {
): Boolean {
integrationRepository.callService(
action.templateId.split(".")[0],
if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON)
if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON) {
if ((action as? BooleanAction)?.newState == true) "turn_on" else "turn_off"
else if ((action as? BooleanAction)?.newState == true) "start" else "return_to_base",
} else if ((action as? BooleanAction)?.newState == true) "start" else "return_to_base",
hashMapOf(
"entity_id" to action.templateId
)

View file

@ -126,8 +126,9 @@ class LaunchActivity : AppCompatActivity(), LaunchView {
notificationsEnabled
)
}
} else
} else {
Log.e(TAG, "onOnboardingComplete: Activity result returned null intent data")
}
}
}

View file

@ -47,8 +47,10 @@ object NFCUtil {
fun <T> enableNFCInForeground(nfcAdapter: NfcAdapter, activity: Activity, classType: Class<T>) {
val pendingIntent = PendingIntent.getActivity(
activity, 0,
Intent(activity, classType).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE
activity,
0,
Intent(activity, classType).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_MUTABLE
)
val nfcIntentFilter = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
val filters = arrayOf(nfcIntentFilter)

View file

@ -46,8 +46,9 @@ class NfcSetupActivity : BaseActivity() {
fun newInstance(context: Context, tagId: String? = null, messageId: Int = -1): Intent {
return Intent(context, NfcSetupActivity::class.java).apply {
putExtra(EXTRA_MESSAGE_ID, messageId)
if (tagId != null)
if (tagId != null) {
putExtra(EXTRA_TAG_VALUE, tagId)
}
}
}
}

View file

@ -44,8 +44,11 @@ class TagReaderActivity : BaseActivity() {
val isNfcTag = intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED
val url =
if (isNfcTag) NFCUtil.extractUrlFromNFCIntent(intent)
else intent.data
if (isNfcTag) {
NFCUtil.extractUrlFromNFCIntent(intent)
} else {
intent.data
}
try {
handleTag(url, isNfcTag)
} catch (e: Exception) {

View file

@ -69,8 +69,11 @@ fun LoadNfcView(
title = { Text(stringResource(commonR.string.nfc_title_settings)) },
navigationIcon = {
IconButton(onClick = {
if (canNavigateUp.value) navController.navigateUp()
else pressedUpAtRoot()
if (canNavigateUp.value) {
navController.navigateUp()
} else {
pressedUpAtRoot()
}
}) {
Icon(
imageVector = Icons.Outlined.ArrowBack,
@ -116,7 +119,9 @@ fun LoadNfcView(
identifier = viewModel.nfcTagIdentifier,
onSetIdentifier = if (viewModel.nfcIdentifierIsEditable) {
{ viewModel.setTagIdentifier(it) }
} else null
} else {
null
}
)
}
composable(NfcSetupActivity.NAV_EDIT) {

View file

@ -20,7 +20,7 @@ import io.homeassistant.companion.android.common.R as commonR
fun NfcWelcomeView(
isNfcEnabled: Boolean,
onReadClicked: () -> Unit,
onWriteClicked: () -> Unit,
onWriteClicked: () -> Unit
) {
LazyColumn(contentPadding = PaddingValues(all = 16.dp)) {
item {

View file

@ -57,12 +57,15 @@ fun NfcWriteView(
) {
Image(
asset = CommunityMaterial.Icon3.cmd_nfc_tap,
colorFilter = ColorFilter.tint(MaterialTheme.colors.onSurface),
colorFilter = ColorFilter.tint(MaterialTheme.colors.onSurface)
)
Text(
text =
if (isNfcEnabled) stringResource(commonR.string.nfc_write_tag_instructions, identifier ?: "")
else stringResource(commonR.string.nfc_write_tag_turnon),
if (isNfcEnabled) {
stringResource(commonR.string.nfc_write_tag_instructions, identifier ?: "")
} else {
stringResource(commonR.string.nfc_write_tag_turnon)
},
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth(0.75f)

View file

@ -229,8 +229,14 @@ class MessagingManager @Inject constructor(
)
val FORCE_COMMANDS = listOf(FORCE_OFF, FORCE_ON)
val MEDIA_COMMANDS = listOf(
MEDIA_FAST_FORWARD, MEDIA_NEXT, MEDIA_PAUSE, MEDIA_PLAY,
MEDIA_PLAY_PAUSE, MEDIA_PREVIOUS, MEDIA_REWIND, MEDIA_STOP
MEDIA_FAST_FORWARD,
MEDIA_NEXT,
MEDIA_PAUSE,
MEDIA_PLAY,
MEDIA_PLAY_PAUSE,
MEDIA_PREVIOUS,
MEDIA_REWIND,
MEDIA_STOP
)
// Video Values
@ -249,7 +255,6 @@ class MessagingManager @Inject constructor(
private val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job())
fun handleMessage(notificationData: Map<String, String>, source: String) {
var now = System.currentTimeMillis()
var jsonData = notificationData
val notificationId: Long
@ -310,9 +315,9 @@ class MessagingManager @Inject constructor(
when (jsonData[NotificationData.MESSAGE]) {
COMMAND_DND -> {
if (jsonData[NotificationData.COMMAND] in DND_COMMANDS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -345,9 +350,9 @@ class MessagingManager @Inject constructor(
}
}
COMMAND_BROADCAST_INTENT -> {
if (!jsonData[INTENT_ACTION].isNullOrEmpty() && !jsonData[INTENT_PACKAGE_NAME].isNullOrEmpty())
if (!jsonData[INTENT_ACTION].isNullOrEmpty() && !jsonData[INTENT_PACKAGE_NAME].isNullOrEmpty()) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -360,9 +365,9 @@ class MessagingManager @Inject constructor(
COMMAND_VOLUME_LEVEL -> {
if (!jsonData[NotificationData.MEDIA_STREAM].isNullOrEmpty() && jsonData[NotificationData.MEDIA_STREAM] in CHANNEL_VOLUME_STREAM &&
!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null
)
) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -377,9 +382,9 @@ class MessagingManager @Inject constructor(
!jsonData[NotificationData.COMMAND].isNullOrEmpty() &&
jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS &&
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
)
) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -410,9 +415,9 @@ class MessagingManager @Inject constructor(
!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] == HIGH_ACCURACY_SET_UPDATE_INTERVAL &&
jsonData[HIGH_ACCURACY_UPDATE_INTERVAL]?.toIntOrNull() != null && jsonData[HIGH_ACCURACY_UPDATE_INTERVAL]?.toInt()!! >= 5
)
)
) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -423,9 +428,9 @@ class MessagingManager @Inject constructor(
}
}
COMMAND_ACTIVITY -> {
if (!jsonData[INTENT_ACTION].isNullOrEmpty())
if (!jsonData[INTENT_ACTION].isNullOrEmpty()) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -449,9 +454,9 @@ class MessagingManager @Inject constructor(
(appLockTimeoutPresent && (appLockTimeoutValue == null || appLockTimeoutValue < 0)) ||
(homeBypassEnablePresent && homeBypassEnableValue == null)
if (!invalid)
if (!invalid) {
handleDeviceCommands(jsonData)
else {
} else {
mainScope.launch {
Log.d(
TAG,
@ -531,20 +536,22 @@ class MessagingManager @Inject constructor(
}
TextToSpeechData.COMMAND_STOP_TTS -> stopTTS()
COMMAND_AUTO_SCREEN_BRIGHTNESS -> {
if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS)
if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS) {
handleDeviceCommands(jsonData)
else
} else {
mainScope.launch {
sendNotification(jsonData)
}
}
}
COMMAND_SCREEN_BRIGHTNESS_LEVEL, COMMAND_SCREEN_OFF_TIMEOUT -> {
if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null)
if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null) {
handleDeviceCommands(jsonData)
else
} else {
mainScope.launch {
sendNotification(jsonData)
}
}
}
else -> Log.d(TAG, "No command received")
}
@ -633,8 +640,9 @@ class MessagingManager @Inject constructor(
addExtrasToIntent(intent, extras)
}
intent.`package` = packageName
if (!packageName.isNullOrEmpty() && !className.isNullOrEmpty())
if (!packageName.isNullOrEmpty() && !className.isNullOrEmpty()) {
intent.setClassName(packageName, className)
}
Log.d(TAG, "Sending broadcast intent")
context.sendBroadcast(intent)
} catch (e: Exception) {
@ -684,10 +692,11 @@ class MessagingManager @Inject constructor(
}
}
@Suppress("DEPRECATION")
if (command == DeviceCommandData.TURN_OFF)
if (command == DeviceCommandData.TURN_OFF) {
bluetoothAdapter?.disable()
else if (command == DeviceCommandData.TURN_ON)
} else if (command == DeviceCommandData.TURN_ON) {
bluetoothAdapter?.enable()
}
}
COMMAND_HIGH_ACCURACY_MODE -> {
when (command) {
@ -703,9 +712,9 @@ class MessagingManager @Inject constructor(
}
COMMAND_ACTIVITY -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(context))
if (!Settings.canDrawOverlays(context)) {
notifyMissingPermission(message.toString())
else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED && data["tag"] == Intent.ACTION_CALL) {
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED && data["tag"] == Intent.ACTION_CALL) {
Handler(Looper.getMainLooper()).post {
Toast.makeText(
context,
@ -714,10 +723,12 @@ class MessagingManager @Inject constructor(
).show()
}
navigateAppDetails()
} else
} else {
processActivityCommand(data)
} else
}
} else {
processActivityCommand(data)
}
}
COMMAND_APP_LOCK -> {
mainScope.launch {
@ -726,12 +737,14 @@ class MessagingManager @Inject constructor(
}
COMMAND_WEBVIEW -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(context))
if (!Settings.canDrawOverlays(context)) {
notifyMissingPermission(message.toString())
else
} else {
openWebview(command, data)
} else
}
} else {
openWebview(command, data)
}
}
COMMAND_SCREEN_ON -> {
if (!command.isNullOrEmpty()) {
@ -756,21 +769,23 @@ class MessagingManager @Inject constructor(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
if (!NotificationManagerCompat.getEnabledListenerPackages(context)
.contains(context.packageName)
)
) {
notifyMissingPermission(message.toString())
else {
} else {
processMediaCommand(data)
}
}
}
COMMAND_LAUNCH_APP -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(context))
if (!Settings.canDrawOverlays(context)) {
notifyMissingPermission(message.toString())
else
} else {
launchApp(data)
} else
}
} else {
launchApp(data)
}
}
COMMAND_PERSISTENT_CONNECTION -> {
togglePersistentConnection(data[PERSISTENT].toString())
@ -778,12 +793,15 @@ class MessagingManager @Inject constructor(
COMMAND_AUTO_SCREEN_BRIGHTNESS, COMMAND_SCREEN_BRIGHTNESS_LEVEL, COMMAND_SCREEN_OFF_TIMEOUT -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(context)) {
if (!processScreenCommands(data))
if (!processScreenCommands(data)) {
mainScope.launch { sendNotification(data) }
} else
}
} else {
notifyMissingPermission(message.toString())
} else if (!processScreenCommands(data))
}
} else if (!processScreenCommands(data)) {
mainScope.launch { sendNotification(data) }
}
}
else -> Log.d(TAG, "No command received")
}
@ -829,12 +847,13 @@ class MessagingManager @Inject constructor(
}
} else {
// Try to guess the correct type
if (value.isDigitsOnly())
if (value.isDigitsOnly()) {
intent.putExtra(chunks[0], value.toInt())
else if ((value.lowercase() == "true") || (value.lowercase() == "false"))
} else if ((value.lowercase() == "true") || (value.lowercase() == "false")) {
intent.putExtra(chunks[0], value.toBoolean())
else
} else {
intent.putExtra(chunks[0], value)
}
}
}
}
@ -858,7 +877,6 @@ class MessagingManager @Inject constructor(
groupId = group.hashCode()
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val notification = notificationManagerCompat.getActiveNotification(tag, messageId)
if (notification != null && notification.isGroup) {
previousGroup = NotificationData.GROUP_PREFIX + notification.tag
@ -1020,8 +1038,9 @@ class MessagingManager @Inject constructor(
} else {
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
}
if (data[NotificationData.ALERT_ONCE].toBoolean())
if (data[NotificationData.ALERT_ONCE].toBoolean()) {
builder.setOnlyAlertOnce(true)
}
}
private fun handleLegacyLedColor(
@ -1051,7 +1070,6 @@ class MessagingManager @Inject constructor(
builder: NotificationCompat.Builder,
data: Map<String, String>
) {
// Use importance property for legacy priority support
val priority = data[NotificationData.IMPORTANCE]
@ -1089,8 +1107,9 @@ class MessagingManager @Inject constructor(
) {
if (!group.isNullOrBlank()) {
builder.setGroup(group)
if (alertOnce == true)
if (alertOnce == true) {
builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
}
}
}
@ -1162,8 +1181,9 @@ class MessagingManager @Inject constructor(
withContext(
Dispatchers.IO
) {
if (url == null)
if (url == null) {
return@withContext null
}
var image: Bitmap? = null
try {
@ -1410,18 +1430,20 @@ class MessagingManager @Inject constructor(
Intent.parseUri(uri, Intent.URI_INTENT_SCHEME)
}
uri.startsWith(SETTINGS_PREFIX) -> {
if (uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY)
if (uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY) {
SettingsActivity.newInstance(context)
else
} else {
WebViewActivity.newInstance(context, null, serverId)
}
}
UrlHandler.isAbsoluteUrl(uri) || uri.startsWith(DEEP_LINK_PREFIX) -> {
Intent(Intent.ACTION_VIEW).apply {
this.data = Uri.parse(
if (uri.startsWith(DEEP_LINK_PREFIX))
if (uri.startsWith(DEEP_LINK_PREFIX)) {
uri.removePrefix(DEEP_LINK_PREFIX)
else
} else {
uri
}
)
}
}
@ -1430,8 +1452,9 @@ class MessagingManager @Inject constructor(
}
} ?: WebViewActivity.newInstance(context, null, serverId)
if (uri.startsWith(SETTINGS_PREFIX) && uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY)
if (uri.startsWith(SETTINGS_PREFIX) && uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY) {
intent.putExtra("fragment", NOTIFICATION_HISTORY)
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (!otherApp) {
@ -1452,10 +1475,12 @@ class MessagingManager @Inject constructor(
val marketIntent = Intent(Intent.ACTION_VIEW)
marketIntent.data = Uri.parse(MARKET_PREFIX + if (uri.startsWith(INTENT_PREFIX)) intent.`package`.toString() else uri.removePrefix(APP_PREFIX))
marketIntent
} else
} else {
intent
} else
intent,
}
} else {
intent
},
PendingIntent.FLAG_IMMUTABLE
)
}
@ -1606,10 +1631,11 @@ class MessagingManager @Inject constructor(
private fun adjustVolumeStream(stream: Int, volume: Int, audioManager: AudioManager) {
var volumeLevel = volume
if (volumeLevel > audioManager.getStreamMaxVolume(stream))
if (volumeLevel > audioManager.getStreamMaxVolume(stream)) {
volumeLevel = audioManager.getStreamMaxVolume(stream)
else if (volumeLevel < 0)
} else if (volumeLevel < 0) {
volumeLevel = 0
}
audioManager.setStreamVolume(
stream,
volumeLevel,
@ -1625,10 +1651,12 @@ class MessagingManager @Inject constructor(
val intentUri = if (!data[INTENT_URI].isNullOrEmpty()) Uri.parse(data[INTENT_URI]) else null
val intent = if (intentUri != null) Intent(action, intentUri) else Intent(action)
val type = data[INTENT_TYPE]
if (!type.isNullOrEmpty())
if (!type.isNullOrEmpty()) {
intent.type = type
if (!className.isNullOrEmpty() && !packageName.isNullOrEmpty())
}
if (!className.isNullOrEmpty() && !packageName.isNullOrEmpty()) {
intent.setClassName(packageName, className)
}
val extras = data[INTENT_EXTRAS]
if (!extras.isNullOrEmpty()) {
addExtrasToIntent(intent, extras)
@ -1637,9 +1665,9 @@ class MessagingManager @Inject constructor(
if (!packageName.isNullOrEmpty()) {
intent.setPackage(packageName)
context.startActivity(intent)
} else if (intent.resolveActivity(context.packageManager) != null)
} else if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
else
} else {
mainScope.launch {
Log.d(
TAG,
@ -1647,6 +1675,7 @@ class MessagingManager @Inject constructor(
)
sendNotification(data)
}
}
} catch (e: Exception) {
Log.e(TAG, "Unable to send activity intent please check command format", e)
Handler(Looper.getMainLooper()).post {
@ -1665,10 +1694,11 @@ class MessagingManager @Inject constructor(
) {
try {
val serverId = data[THIS_SERVER_ID]!!.toInt()
val intent = if (title.isNullOrEmpty())
val intent = if (title.isNullOrEmpty()) {
WebViewActivity.newInstance(context, null, serverId)
else
} else {
WebViewActivity.newInstance(context, title, serverId)
}
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
context.startActivity(intent)
@ -1680,9 +1710,9 @@ class MessagingManager @Inject constructor(
private fun launchApp(data: Map<String, String>) {
try {
val launchIntent = context.packageManager.getLaunchIntentForPackage(data[PACKAGE_NAME]!!)
if (launchIntent != null)
if (launchIntent != null) {
context.startActivity(launchIntent)
else {
} else {
Log.w(TAG, "No intent to launch app found, opening app store")
val marketIntent = Intent(Intent.ACTION_VIEW)
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@ -1764,10 +1794,11 @@ class MessagingManager @Inject constructor(
when (data[NotificationData.MESSAGE].toString()) {
COMMAND_SCREEN_BRIGHTNESS_LEVEL -> command!!.toInt().coerceIn(0, 255)
COMMAND_AUTO_SCREEN_BRIGHTNESS -> {
if (command == DeviceCommandData.TURN_ON)
if (command == DeviceCommandData.TURN_ON) {
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
else
} else {
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
}
}
else -> command!!.toInt()
}

View file

@ -44,7 +44,6 @@ class NotificationActionReceiver : BroadcastReceiver() {
lateinit var notificationDao: NotificationDao
override fun onReceive(context: Context, intent: Intent) {
val notificationAction =
intent.getParcelableExtra<NotificationAction>(EXTRA_NOTIFICATION_ACTION)

View file

@ -29,7 +29,6 @@ class NotificationDeleteReceiver : BroadcastReceiver() {
lateinit var notificationDao: NotificationDao
override fun onReceive(context: Context, intent: Intent) {
val hashData = intent.getSerializableExtra(EXTRA_DATA) as HashMap<String, *>
val group = intent.getStringExtra(EXTRA_NOTIFICATION_GROUP)
val groupId = intent.getIntExtra(EXTRA_NOTIFICATION_GROUP_ID, -1)

View file

@ -39,7 +39,9 @@ class OnboardingActivity : AppCompatActivity() {
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
NotificationManagerCompat.from(this).areNotificationsEnabled()
)
} else false
} else {
false
}
viewModel.deviceIsWatch = input.isWatch
if (savedInstanceState == null) {

View file

@ -92,10 +92,11 @@ class AuthenticationFragment : Fragment() {
requireContext().getString(
commonR.string.error_http_generic,
error?.errorCode,
if (error?.description.isNullOrBlank())
if (error?.description.isNullOrBlank()) {
commonR.string.no_description
else
} else {
error?.description
}
),
null,
error
@ -131,12 +132,14 @@ class AuthenticationFragment : Fragment() {
requireContext().getString(
commonR.string.error_http_generic,
errorResponse?.statusCode,
if (errorResponse?.reasonPhrase.isNullOrBlank())
if (errorResponse?.reasonPhrase.isNullOrBlank()) {
requireContext().getString(commonR.string.no_description)
else
} else {
errorResponse?.reasonPhrase
}
),
null, null
null,
null
)
}
}

View file

@ -30,8 +30,9 @@ class HomeAssistantSearcher constructor(
private var multicastLock: WifiManager.MulticastLock? = null
fun beginSearch() {
if (isSearching)
if (isSearching) {
return
}
isSearching = true
try {
nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, this)
@ -54,8 +55,9 @@ class HomeAssistantSearcher constructor(
}
fun stopSearch() {
if (!isSearching)
if (!isSearching) {
return
}
isSearching = false
try {
nsdManager.stopServiceDiscovery(this)

View file

@ -61,7 +61,6 @@ class MobileAppIntegrationFragment : Fragment() {
private fun onLocationTrackingChanged(isChecked: Boolean) {
var checked = isChecked
if (isChecked) {
val locationEnabled = DisabledLocationHandler.isLocationEnabled(requireContext())
val permissionOk = LocationSensorManager().checkPermission(
requireContext(),

View file

@ -40,7 +40,6 @@ fun ManualSetupView(
.fillMaxWidth()
.padding(16.dp)
) {
OnboardingHeaderView(
icon = CommunityMaterial.Icon3.cmd_web,
title = stringResource(id = commonR.string.manual_title)

View file

@ -30,8 +30,11 @@ class NotificationPermissionFragment : Fragment() {
Log.i(TAG, "Notification permission was ${if (isGranted) "granted" else "not granted"}")
viewModel.setNotifications(isGranted)
if (isGranted) onComplete()
else showPermissionDeniedDialog()
if (isGranted) {
onComplete()
} else {
showPermissionDeniedDialog()
}
}
override fun onCreateView(

View file

@ -12,10 +12,11 @@ class Tile10Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile11Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile12Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile13Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile14Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile15Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile16Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile17Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile18Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile19Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -8,10 +8,11 @@ import androidx.annotation.RequiresApi
class Tile1Service : TileExtensions() {
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile20Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile21Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile22Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile23Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile24Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile25Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile26Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile27Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile28Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile29Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -8,10 +8,11 @@ import androidx.annotation.RequiresApi
class Tile2Service : TileExtensions() {
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile30Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile31Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile32Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile33Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile34Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile35Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile36Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile37Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile38Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile39Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -8,10 +8,11 @@ import androidx.annotation.RequiresApi
class Tile3Service : TileExtensions() {
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile40Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile4Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile5Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile6Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile7Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile8Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -12,10 +12,11 @@ class Tile9Service : TileExtensions() {
}
override fun getTile(): Tile? {
return if (qsTile != null)
return if (qsTile != null) {
qsTile
else
} else {
null
}
}
override fun getTileId(): String {

View file

@ -157,15 +157,18 @@ abstract class TileExtensions : TileService() {
null
}
}
} else null
} else {
null
}
if (tileData.entityId.split('.')[0] in toggleDomainsWithLock) {
tile.state = when {
state?.state in validActiveStates -> Tile.STATE_ACTIVE
state?.state != null && state.state !in validActiveStates -> Tile.STATE_INACTIVE
else -> Tile.STATE_UNAVAILABLE
}
} else
} else {
tile.state = Tile.STATE_INACTIVE
}
getTileIcon(tileData.iconId, state, context)?.let { icon ->
tile.icon = Icon.createWithBitmap(icon)
@ -180,8 +183,11 @@ abstract class TileExtensions : TileService() {
Log.d(TAG, "No tile data found for tile ID: $tileId")
}
tile.state =
if (serverManager.isRegistered()) Tile.STATE_INACTIVE
else Tile.STATE_UNAVAILABLE
if (serverManager.isRegistered()) {
Tile.STATE_INACTIVE
} else {
Tile.STATE_UNAVAILABLE
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
tile.subtitle = getString(commonR.string.tile_not_setup)
}
@ -207,8 +213,9 @@ abstract class TileExtensions : TileService() {
if (tileData?.shouldVibrate == true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vm?.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
} else
} else {
vm?.vibrate(500)
}
}
if (tileData?.authRequired == true && isSecure) {
unlockAndRun {
@ -238,10 +245,11 @@ abstract class TileExtensions : TileService() {
in toggleDomains -> "toggle"
"lock" -> {
val state = serverManager.integrationRepository(tileData.serverId).getEntity(tileData.entityId)
if (state?.state == "locked")
if (state?.state == "locked") {
"unlock"
else
} else {
"lock"
}
}
else -> "turn_on"
},
@ -276,8 +284,9 @@ abstract class TileExtensions : TileService() {
val vm = getSystemService<Vibrator>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vm?.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK))
} else
} else {
vm?.vibrate(1000)
}
}
withContext(Dispatchers.Main) {
Toast.makeText(

View file

@ -52,9 +52,9 @@ class DevicePolicyManager : SensorManager {
}
private fun updateWorkProfile(context: Context) {
if (!isEnabled(context, isWorkProfile))
if (!isEnabled(context, isWorkProfile)) {
return
}
onSensorUpdated(
context,

View file

@ -45,13 +45,13 @@ class DynamicColorSensorManager : SensorManager {
}
private fun updateAccentColor(context: Context) {
if (!isEnabled(context, accentColorSensor))
if (!isEnabled(context, accentColorSensor)) {
return
}
val dynamicColorContext = DynamicColors.wrapContextIfAvailable(context)
val attrsToResolve = intArrayOf(
android.R.attr.colorAccent, // 0
android.R.attr.colorAccent // 0
)
val test = dynamicColorContext.obtainStyledAttributes(attrsToResolve)
val accent = test.getColor(0, 0)

View file

@ -37,6 +37,7 @@ class LastAppSensorManager : SensorManager {
override fun hasSensor(context: Context): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
}
@RequiresApi(Build.VERSION_CODES.M)
override fun requiredPermissions(sensorId: String): Array<String> {
return arrayOf(Manifest.permission.PACKAGE_USAGE_STATS)
@ -51,8 +52,9 @@ class LastAppSensorManager : SensorManager {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private fun updateLastApp(context: Context) {
if (!isEnabled(context, last_used))
if (!isEnabled(context, last_used)) {
return
}
val usageStats = context.getSystemService<UsageStatsManager>()!!
val current = System.currentTimeMillis()

View file

@ -107,8 +107,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
updateActiveNotificationCount()
if (!isEnabled(applicationContext, lastNotification))
if (!isEnabled(applicationContext, lastNotification)) {
return
}
val allowPackages = getSetting(
applicationContext,
@ -141,8 +142,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
.plus("category" to sbn.notification.category)
.toMutableMap()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
attr["channel_id"] = sbn.notification.channelId
}
// Attempt to use the text of the notification but fallback to package name if all else fails.
val state = attr["android.text"] ?: attr["android.title"] ?: sbn.packageName
@ -153,7 +155,7 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
state.toString().take(255),
lastNotification.statelessIcon,
attr,
forceUpdate = true,
forceUpdate = true
)
// Need to send update!
@ -165,8 +167,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
updateActiveNotificationCount()
if (!isEnabled(applicationContext, lastRemovedNotification))
if (!isEnabled(applicationContext, lastRemovedNotification)) {
return
}
val allowPackages = getSetting(
applicationContext,
@ -199,8 +202,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
.plus("category" to sbn.notification.category)
.toMutableMap()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
attr["channel_id"] = sbn.notification.channelId
}
// Attempt to use the text of the notification but fallback to package name if all else fails.
val state = attr["android.text"] ?: attr["android.title"] ?: sbn.packageName
@ -211,7 +215,7 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
state.toString().take(255),
lastRemovedNotification.statelessIcon,
attr,
forceUpdate = true,
forceUpdate = true
)
// Need to send update!
@ -219,8 +223,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
}
private fun updateActiveNotificationCount() {
if (!isEnabled(applicationContext, activeNotificationCount) || !listenerConnected)
if (!isEnabled(applicationContext, activeNotificationCount) || !listenerConnected) {
return
}
try {
val attr: MutableMap<String, Any?> = mutableMapOf()
@ -232,8 +237,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
.plus("${item.packageName}_${item.id}_group_id" to item.notification.group)
.plus("${item.packageName}_${item.id}_category" to item.notification.category)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
attr["${item.packageName}_${item.id}_channel_id"] = item.notification.channelId
}
}
onSensorUpdated(
applicationContext,
@ -248,8 +254,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
}
private fun updateMediaSession(context: Context) {
if (!isEnabled(context, mediaSession))
if (!isEnabled(context, mediaSession)) {
return
}
val mediaSessionManager = context.getSystemService<MediaSessionManager>()!!
val mediaList = mediaSessionManager.getActiveSessions(ComponentName(context, NotificationSensorManager::class.java))
@ -307,8 +314,11 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager {
bundle.keySet().associate { key ->
val keyValue = when (val value = bundle.get(key)) {
is Array<*> -> {
if (value.all { it is Bundle }) value.map { mappedBundle(it as Bundle) ?: value }
else value.toList()
if (value.all { it is Bundle }) {
value.map { mappedBundle(it as Bundle) ?: value }
} else {
value.toList()
}
}
is BooleanArray -> value.toList()
is Bundle -> mappedBundle(value) ?: value

View file

@ -59,8 +59,9 @@ class QuestSensorManager : SensorManager {
}
private fun updateHeadsetMount(context: Context, intent: Intent) {
if (!isEnabled(context, headsetMounted))
if (!isEnabled(context, headsetMounted)) {
return
}
val state: Boolean = getHeadsetState(intent)

View file

@ -110,7 +110,7 @@ class SensorReceiver : SensorReceiverBase() {
AudioManager.RINGER_MODE_CHANGED_ACTION to AudioSensorManager.audioSensor.id,
Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE to DevicePolicyManager.isWorkProfile.id,
Intent.ACTION_MANAGED_PROFILE_AVAILABLE to DevicePolicyManager.isWorkProfile.id,
WifiManager.WIFI_STATE_CHANGED_ACTION to NetworkSensorManager.wifiState.id,
WifiManager.WIFI_STATE_CHANGED_ACTION to NetworkSensorManager.wifiState.id
)
override fun getSensorSettingsIntent(

View file

@ -88,8 +88,11 @@ class SettingsActivity : BaseActivity() {
R.id.content,
when {
settingsNavigation == "websocket" ->
if (serverManager.defaultServers.size == 1) WebsocketSettingFragment::class.java
else SettingsFragment::class.java
if (serverManager.defaultServers.size == 1) {
WebsocketSettingFragment::class.java
} else {
SettingsFragment::class.java
}
settingsNavigation == "notification_history" -> NotificationHistoryFragment::class.java
settingsNavigation?.startsWith("sensors/") == true -> SensorDetailFragment::class.java
settingsNavigation?.startsWith("tiles/") == true -> ManageTilesFragment::class.java
@ -105,8 +108,12 @@ class SettingsActivity : BaseActivity() {
val servers = serverManager.defaultServers
if (servers.size == 1) {
Bundle().apply { putInt(WebsocketSettingFragment.EXTRA_SERVER, servers[0].id) }
} else null
} else null
} else {
null
}
} else {
null
}
)
}
}

View file

@ -221,7 +221,6 @@ class SettingsFragment(
if (BuildConfig.FLAVOR == "full") {
findPreference<Preference>("notification_rate_limit")?.let {
lifecycleScope.launch(Dispatchers.Main) {
// Runs in IO Dispatcher
val rateLimits = presenter.getNotificationRateLimits()
@ -263,9 +262,11 @@ class SettingsFragment(
}
findPreference<Preference>("changelog_github")?.let {
val link = if (BuildConfig.VERSION_NAME.startsWith("LOCAL"))
val link = if (BuildConfig.VERSION_NAME.startsWith("LOCAL")) {
"https://github.com/home-assistant/android/releases"
else "https://github.com/home-assistant/android/releases/tag/${BuildConfig.VERSION_NAME.replace("-full", "").replace("-minimal", "")}"
} else {
"https://github.com/home-assistant/android/releases/tag/${BuildConfig.VERSION_NAME.replace("-full", "").replace("-minimal", "")}"
}
it.summary = link
it.intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
}

View file

@ -118,8 +118,11 @@ class SettingsPresenterImpl @Inject constructor(
override suspend fun getNotificationRateLimits(): RateLimitResponse? = withContext(Dispatchers.IO) {
try {
if (serverManager.isRegistered()) serverManager.integrationRepository().getNotificationRateLimits()
else null
if (serverManager.isRegistered()) {
serverManager.integrationRepository().getNotificationRateLimits()
} else {
null
}
} catch (e: Exception) {
Log.d(TAG, "Unable to get rate limits")
return@withContext null

View file

@ -31,7 +31,9 @@ class LanguagesManager @Inject constructor(
if (lang.isNullOrEmpty()) {
prefs.saveLang(DEF_LOCALE)
DEF_LOCALE
} else lang
} else {
lang
}
}
}
}
@ -42,8 +44,11 @@ class LanguagesManager @Inject constructor(
val currentLang = getCurrentLang()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val languages =
if (lang == DEF_LOCALE) LocaleListCompat.getEmptyLocaleList()
else LocaleListCompat.forLanguageTags(lang)
if (lang == DEF_LOCALE) {
LocaleListCompat.getEmptyLocaleList()
} else {
LocaleListCompat.forLanguageTags(lang)
}
AppCompatDelegate.setApplicationLocales(languages) // Applying will also save it
} else if (currentLang != lang) {
prefs.saveLang(lang)
@ -59,8 +64,11 @@ class LanguagesManager @Inject constructor(
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.TIRAMISU) {
val lang = getCurrentLang()
val languages =
if (lang == DEF_LOCALE) LocaleListCompat.getEmptyLocaleList()
else LocaleListCompat.forLanguageTags(lang)
if (lang == DEF_LOCALE) {
LocaleListCompat.getEmptyLocaleList()
} else {
LocaleListCompat.forLanguageTags(lang)
}
AppCompatDelegate.setApplicationLocales(languages)
} // else on Android 13+ the system will manage the app's language
}
@ -72,8 +80,11 @@ class LanguagesManager @Inject constructor(
// First run on Android 13: save in AndroidX, update app preference
val languages =
if (lang == DEF_LOCALE) LocaleListCompat.getEmptyLocaleList()
else LocaleListCompat.forLanguageTags(lang)
if (lang == DEF_LOCALE) {
LocaleListCompat.getEmptyLocaleList()
} else {
LocaleListCompat.forLanguageTags(lang)
}
AppCompatDelegate.setApplicationLocales(languages)
prefs.saveLang(SYSTEM_MANAGES_LOCALE)
}

View file

@ -78,8 +78,11 @@ class LogFragment : Fragment() {
override fun onTabReselected(tab: TabLayout.Tab?) {
(requireView().findViewById<ScrollView>(R.id.logScrollview))?.apply {
post {
if (tab?.id == R.id.logTabCrash) fullScroll(ScrollView.FOCUS_UP)
else fullScroll(ScrollView.FOCUS_DOWN)
if (tab?.id == R.id.logTabCrash) {
fullScroll(ScrollView.FOCUS_UP)
} else {
fullScroll(ScrollView.FOCUS_DOWN)
}
}
}
}
@ -160,7 +163,6 @@ class LogFragment : Fragment() {
fLogFile.appendText(currentLog)
if (fLogFile.exists()) {
val uriToLog: Uri = FileProvider.getUriForFile(requireContext(), requireContext().packageName + ".provider", fLogFile)
val sendIntent: Intent = Intent().apply {

View file

@ -52,8 +52,9 @@ class NotificationDetailFragment : Fragment() {
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_delete)
if (item.itemId == R.id.action_delete) {
deleteConfirmation()
}
return super.onOptionsItemSelected(item)
}

View file

@ -70,8 +70,9 @@ class NotificationHistoryFragment : PreferenceFragmentCompat() {
var searchList: Array<NotificationItem> = emptyArray()
if (!query.isNullOrEmpty()) {
for (item in allNotifications) {
if (item.message.contains(query, true))
if (item.message.contains(query, true)) {
searchList += item
}
}
prefCategory?.title = getString(commonR.string.search_results)
reloadNotifications(searchList, prefCategory)
@ -96,8 +97,9 @@ class NotificationHistoryFragment : PreferenceFragmentCompat() {
}
item.isChecked = !item.isChecked
filterNotifications(filterValue, notificationDao, prefCategory)
} else if (item.itemId == R.id.action_delete)
} else if (item.itemId == R.id.action_delete) {
deleteAllConfirmation(notificationDao)
}
return super.onOptionsItemSelected(item)
}

View file

@ -222,13 +222,19 @@ class ManageTilesViewModel @Inject constructor(
selectedTileId = it?.id ?: 0
selectedTileAdded = it?.added ?: false
selectedServerId =
if (it?.serverId == null || it.serverId == 0) serverManager.getServer()?.id ?: 0
else it.serverId
if (it?.serverId == null || it.serverId == 0) {
serverManager.getServer()?.id ?: 0
} else {
it.serverId
}
selectedShouldVibrate = it?.shouldVibrate ?: false
tileAuthRequired = it?.authRequired ?: false
submitButtonLabel =
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2 || it?.added == true) commonR.string.tile_save
else commonR.string.tile_add
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2 || it?.added == true) {
commonR.string.tile_save
} else {
commonR.string.tile_add
}
loadEntities(selectedServerId)
if (it?.isSetup == true) {
updateExistingTileFields(it)
@ -278,8 +284,11 @@ class ManageTilesViewModel @Inject constructor(
tileAuthRequired = currentTile.authRequired
selectIcon(
currentTile.iconId?.let {
if (::iconPack.isInitialized) iconPack.getIcon(it)
else null
if (::iconPack.isInitialized) {
iconPack.getIcon(it)
} else {
null
}
}
)
}

View file

@ -136,13 +136,16 @@ class SensorDetailFragment : Fragment() {
DisabledLocationHandler.showLocationDisabledWarnDialog(requireActivity(), it.sensors)
} else {
LocationPermissionInfoHandler.showLocationPermInfoDialogIfNeeded(
requireContext(), it.permissions!!,
requireContext(),
it.permissions!!,
continueYesCallback = {
requestForServer = it.serverId
permissionsRequest.launch(
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
it.permissions.toSet().minus(Manifest.permission.ACCESS_BACKGROUND_LOCATION).toTypedArray()
} else it.permissions
} else {
it.permissions
}
)
}
)

View file

@ -102,6 +102,7 @@ class SensorDetailViewModel @Inject constructor(
/** A list of all sensors (for each server) with states */
var sensors by mutableStateOf<List<SensorWithAttributes>>(emptyList())
private set
/** A sensor for displaying the main state in the UI */
var sensor by mutableStateOf<SensorWithAttributes?>(null)
private set
@ -208,10 +209,12 @@ class SensorDetailViewModel @Inject constructor(
viewModelScope.launch {
updateSensorEntity(isEnabled, serverId)
if (isEnabled) try {
sensorManager?.requestSensorUpdate(getApplication())
} catch (e: Exception) {
Log.e(TAG, "Exception while requesting update for sensor $sensorId", e)
if (isEnabled) {
try {
sensorManager?.requestSensorUpdate(getApplication())
} catch (e: Exception) {
Log.e(TAG, "Exception while requesting update for sensor $sensorId", e)
}
}
}
}
@ -274,8 +277,11 @@ class SensorDetailViewModel @Inject constructor(
private suspend fun updateSensorEntity(isEnabled: Boolean, serverId: Int?) {
val serverIds =
if (serverId == null) serverManager.defaultServers.map { it.id }
else listOf(serverId)
if (serverId == null) {
serverManager.defaultServers.map { it.id }
} else {
listOf(serverId)
}
sensorDao.setSensorEnabled(sensorId, serverIds, isEnabled)
refreshSensorData()
}

View file

@ -106,8 +106,11 @@ fun SensorDetailView(
context.getString(commonR.string.settings)
).let { result ->
if (result == SnackbarResult.ActionPerformed) {
if (it.actionOpensSettings) context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))
else onSetEnabled(true, it.serverId)
if (it.actionOpensSettings) {
context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))
} else {
onSetEnabled(true, it.serverId)
}
}
}
}.launchIn(this)
@ -121,13 +124,15 @@ fun SensorDetailView(
userSetting = viewModel.settingUpdateFrequency,
onDismiss = { sensorUpdateTypeInfo = false }
)
} else viewModel.sensorSettingsDialog?.let {
SensorDetailSettingDialog(
viewModel = viewModel,
state = it,
onDismiss = { viewModel.cancelSettingWithDialog() },
onSubmit = { state -> onDialogSettingSubmitted(state) }
)
} else {
viewModel.sensorSettingsDialog?.let {
SensorDetailSettingDialog(
viewModel = viewModel,
state = it,
onDismiss = { viewModel.cancelSettingWithDialog() },
onSubmit = { state -> onDialogSettingSubmitted(state) }
)
}
}
LazyColumn(modifier = Modifier.padding(contentPadding)) {
if (viewModel.sensorManager != null && viewModel.basicSensor != null) {
@ -214,8 +219,11 @@ fun SensorDetailView(
SensorDetailRow(
title = viewModel.getSettingTranslatedTitle(setting.name),
summary =
if (summaryValues.any()) viewModel.getSettingEntries(setting, summaryValues).joinToString(", ")
else stringResource(commonR.string.none_selected),
if (summaryValues.any()) {
viewModel.getSettingEntries(setting, summaryValues).joinToString(", ")
} else {
stringResource(commonR.string.none_selected)
},
enabled = setting.enabled,
clickable = setting.enabled,
onClick = { onDialogSettingClicked(setting) }
@ -283,8 +291,11 @@ fun SensorDetailTopPanel(
.size(24.dp)
.alpha(if (sensor?.enabled == true) ContentAlpha.high else ContentAlpha.disabled),
colorFilter = ColorFilter.tint(
if (sensor?.enabled == true) colorResource(commonR.color.colorSensorIconEnabled)
else contentColorFor(backgroundColor = MaterialTheme.colors.background)
if (sensor?.enabled == true) {
colorResource(commonR.color.colorSensorIconEnabled)
} else {
contentColorFor(backgroundColor = MaterialTheme.colors.background)
}
)
)
Spacer(modifier = Modifier.width(16.dp))
@ -301,8 +312,11 @@ fun SensorDetailTopPanel(
if (sensor.state.isBlank()) {
stringResource(commonR.string.enabled)
} else {
if (sensor.unitOfMeasurement.isNullOrBlank()) sensor.state
else "${sensor.state} ${sensor.unitOfMeasurement}"
if (sensor.unitOfMeasurement.isNullOrBlank()) {
sensor.state
} else {
"${sensor.state} ${sensor.unitOfMeasurement}"
}
}
} else {
stringResource(commonR.string.disabled)
@ -350,15 +364,21 @@ fun SensorDetailEnableRow(
.heightIn(min = 64.dp)
.clickable { onSetEnabled() }
val switchDescription = stringResource(
if (basicSensor.type == "binary_sensor" || basicSensor.type == "sensor") commonR.string.enable_sensor
else (if (enabled) commonR.string.enabled else commonR.string.disabled)
if (basicSensor.type == "binary_sensor" || basicSensor.type == "sensor") {
commonR.string.enable_sensor
} else {
(if (enabled) commonR.string.enabled else commonR.string.disabled)
}
)
Box(
modifier =
if (enabled) Modifier
.background(colorResource(commonR.color.colorSensorTopEnabled))
.then(enableBarModifier)
else enableBarModifier,
if (enabled) {
Modifier
.background(colorResource(commonR.color.colorSensorTopEnabled))
.then(enableBarModifier)
} else {
enableBarModifier
},
contentAlignment = Alignment.Center
) {
Row(
@ -432,8 +452,11 @@ fun SensorDetailRow(
Text(text = title, style = MaterialTheme.typography.body1)
if (summary != null) {
CompositionLocalProvider(LocalContentAlpha provides (if (enabled) ContentAlpha.medium else ContentAlpha.disabled)) {
if (selectingEnabled) SelectionContainer { Text(text = summary, style = MaterialTheme.typography.body2) }
else Text(text = summary, style = MaterialTheme.typography.body2)
if (selectingEnabled) {
SelectionContainer { Text(text = summary, style = MaterialTheme.typography.body2) }
} else {
Text(text = summary, style = MaterialTheme.typography.body2)
}
}
}
}
@ -479,8 +502,9 @@ fun SensorDetailSettingDialog(
inputValue.value = id
onSubmit(state.copy().apply { setting.value = inputValue.value })
} else {
if (checkedValue.contains(id) && !isChecked) checkedValue.remove(id)
else if (!checkedValue.contains(id) && isChecked) checkedValue.add(id)
if (checkedValue.contains(id) && !isChecked) {
checkedValue.remove(id)
} else if (!checkedValue.contains(id) && isChecked) checkedValue.add(id)
}
}
)
@ -512,7 +536,9 @@ fun SensorDetailSettingDialog(
}
onSubmit(state.copy().apply { setting.value = inputValue.value })
}
} else null, // list is saved when selecting a value
} else {
null
}, // list is saved when selecting a value
contentPadding = if (listSettingDialog) PaddingValues(all = 0.dp) else PaddingValues(horizontal = 24.dp)
)
}

View file

@ -33,7 +33,6 @@ fun SensorListView(
viewModel: SensorSettingsViewModel,
onSensorClicked: (String) -> Unit
) {
LazyColumn {
viewModel.allSensors.forEach { (manager, currentSensors) ->
stickyHeader(
@ -101,8 +100,11 @@ fun SensorRow(
if (dbSensor.state.isBlank()) {
stringResource(commonR.string.enabled)
} else {
if (basicSensor.unitOfMeasurement.isNullOrBlank()) dbSensor.state
else "${dbSensor.state} ${basicSensor.unitOfMeasurement}"
if (basicSensor.unitOfMeasurement.isNullOrBlank()) {
dbSensor.state
} else {
"${dbSensor.state} ${basicSensor.unitOfMeasurement}"
}
}
} else {
stringResource(commonR.string.disabled)

View file

@ -236,16 +236,22 @@ class ServerSettingsFragment : ServerSettingsView, PreferenceFragmentCompat() {
override fun updateExternalUrl(url: String, useCloud: Boolean) {
findPreference<Preference>("connection_external")?.let {
it.summary =
if (useCloud) getString(commonR.string.input_cloud)
else url
if (useCloud) {
getString(commonR.string.input_cloud)
} else {
url
}
}
}
override fun updateSsids(ssids: List<String>) {
findPreference<Preference>("connection_internal_ssids")?.let {
it.summary =
if (ssids.isEmpty()) getString(commonR.string.pref_connection_ssids_empty)
else ssids.joinToString()
if (ssids.isEmpty()) {
getString(commonR.string.pref_connection_ssids_empty)
} else {
ssids.joinToString()
}
}
}
@ -259,13 +265,16 @@ class ServerSettingsFragment : ServerSettingsView, PreferenceFragmentCompat() {
if (DisabledLocationHandler.isLocationEnabled(requireContext())) {
if (!checkPermission(permissionsToCheck)) {
LocationPermissionInfoHandler.showLocationPermInfoDialogIfNeeded(
requireContext(), permissionsToCheck,
requireContext(),
permissionsToCheck,
continueYesCallback = {
requestLocationPermission()
// showSsidSettings() will be called if permission is granted
}
)
} else showSsidSettings()
} else {
showSsidSettings()
}
} else {
if (presenter.isSsidUsed()) {
DisabledLocationHandler.showLocationDisabledWarnDialog(
@ -273,7 +282,8 @@ class ServerSettingsFragment : ServerSettingsView, PreferenceFragmentCompat() {
arrayOf(
getString(commonR.string.pref_connection_wifi)
),
showAsNotification = false, withDisableOption = true
showAsNotification = false,
withDisableOption = true
) {
presenter.clearSsids()
}

View file

@ -132,10 +132,11 @@ class ManageShortcutsViewModel @Inject constructor(
.setShortLabel(shortcutLabel)
.setLongLabel(shortcutDesc)
.setIcon(
if (bitmap != null)
if (bitmap != null) {
Icon.createWithBitmap(bitmap)
else
} else {
Icon.createWithResource(getApplication(), R.drawable.ic_stat_ic_notification_blue)
}
)
.setIntent(intent)
.build()
@ -177,12 +178,14 @@ class ManageShortcutsViewModel @Inject constructor(
shortcuts.last().desc.value = item.longLabel.toString()
shortcuts.last().path.value = item.intent?.action.toString()
shortcuts.last().selectedIcon.value = item.intent?.extras?.getInt("iconId").toString().toIntOrNull() ?: 0
if (shortcuts.last().selectedIcon.value != 0)
if (shortcuts.last().selectedIcon.value != 0) {
shortcuts.last().drawable.value = getTileIcon(shortcuts.last().selectedIcon.value)
if (shortcuts.last().path.value.startsWith("entityId:"))
}
if (shortcuts.last().path.value.startsWith("entityId:")) {
shortcuts.last().type.value = "entityId"
else
} else {
shortcuts.last().type.value = "lovelace"
}
}
}
}
@ -197,12 +200,14 @@ class ManageShortcutsViewModel @Inject constructor(
shortcuts[index].desc.value = item.longLabel.toString()
shortcuts[index].path.value = item.intent?.action.toString()
shortcuts[index].selectedIcon.value = item.intent?.extras?.getInt("iconId").toString().toIntOrNull() ?: 0
if (shortcuts[index].selectedIcon.value != 0)
if (shortcuts[index].selectedIcon.value != 0) {
shortcuts[index].drawable.value = getTileIcon(shortcuts[index].selectedIcon.value)
if (shortcuts[index].path.value.startsWith("entityId:"))
}
if (shortcuts[index].path.value.startsWith("entityId:")) {
shortcuts[index].type.value = "entityId"
else
} else {
shortcuts[index].type.value = "lovelace"
}
}
}
}

Some files were not shown because too many files have changed in this diff Show more