forked from gotify/android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInitializationActivity.kt
More file actions
221 lines (197 loc) · 7.69 KB
/
Copy pathInitializationActivity.kt
File metadata and controls
221 lines (197 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package com.github.gotify.init
import android.Manifest
import android.app.AlarmManager
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.github.gotify.R
import com.github.gotify.Settings
import com.github.gotify.api.ApiException
import com.github.gotify.api.Callback
import com.github.gotify.api.Callback.SuccessCallback
import com.github.gotify.api.ClientFactory
import com.github.gotify.client.model.User
import com.github.gotify.client.model.VersionInfo
import com.github.gotify.login.LoginActivity
import com.github.gotify.messages.MessagesActivity
import com.github.gotify.service.WebSocketService
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.livinglifetechway.quickpermissionskotlin.runWithPermissions
import com.livinglifetechway.quickpermissionskotlin.util.QuickPermissionsOptions
import com.livinglifetechway.quickpermissionskotlin.util.QuickPermissionsRequest
import org.tinylog.kotlin.Logger
internal class InitializationActivity : AppCompatActivity() {
private lateinit var settings: Settings
private var splashScreenActive = true
@RequiresApi(Build.VERSION_CODES.S)
private val activityResultLauncher =
registerForActivityResult(StartActivityForResult()) {
requestAlarmPermissionOrAuthenticate()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settings = Settings(this)
Logger.info("Entering ${javaClass.simpleName}")
installSplashScreen().setKeepOnScreenCondition { splashScreenActive }
if (settings.tokenExists()) {
runWithPostNotificationsPermission {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
// Android 14 and above
requestAlarmPermissionOrAuthenticate()
} else {
// Android 13 and below
tryAuthenticate()
}
}
} else {
showLogin()
}
}
@RequiresApi(Build.VERSION_CODES.S)
private fun requestAlarmPermissionOrAuthenticate() {
val manager = ContextCompat.getSystemService(this, AlarmManager::class.java)
if (manager?.canScheduleExactAlarms() == true) {
tryAuthenticate()
} else {
stopSlashScreen()
alarmDialog()
}
}
private fun showLogin() {
splashScreenActive = false
startActivity(Intent(this, LoginActivity::class.java))
finish()
}
private fun tryAuthenticate() {
ClientFactory.userApiWithToken(settings)
.currentUser()
.enqueue(
Callback.callInUI(
this,
onSuccess = Callback.SuccessBody { user -> authenticated(user) },
onError = { exception -> failed(exception) }
)
)
}
private fun failed(exception: ApiException) {
stopSlashScreen()
when (exception.code) {
0 -> {
dialog(getString(R.string.not_available, settings.url))
return
}
401 -> {
dialog(getString(R.string.auth_failed))
return
}
}
var response = exception.body
response = response.take(200)
dialog(getString(R.string.other_error, settings.url, exception.code, response))
}
private fun dialog(message: String) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.oops)
.setMessage(message)
.setPositiveButton(R.string.retry) { _, _ -> tryAuthenticate() }
.setNegativeButton(R.string.logout) { _, _ -> showLogin() }
.setCancelable(false)
.show()
}
@RequiresApi(Build.VERSION_CODES.S)
private fun alarmDialog() {
MaterialAlertDialogBuilder(this)
.setMessage(getString(R.string.permissions_alarm_prompt))
.setPositiveButton(getString(R.string.permissions_dialog_grant)) { _, _ ->
Intent(
android.provider.Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM,
Uri.parse("package:$packageName")
).apply {
activityResultLauncher.launch(this)
}
}
.setCancelable(false)
.show()
}
private fun authenticated(user: User) {
Logger.info("Authenticated as ${user.name}")
settings.setUser(user.name, user.isAdmin)
requestVersion {
splashScreenActive = false
startActivity(Intent(this, MessagesActivity::class.java))
finish()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this, WebSocketService::class.java))
} else {
startService(Intent(this, WebSocketService::class.java))
}
}
private fun requestVersion(runnable: Runnable) {
requestVersion(
callback = Callback.SuccessBody { version: VersionInfo ->
Logger.info("Server version: ${version.version}@${version.buildDate}")
settings.serverVersion = version.version
runnable.run()
},
errorCallback = { runnable.run() }
)
}
private fun requestVersion(
callback: SuccessCallback<VersionInfo>,
errorCallback: Callback.ErrorCallback
) {
ClientFactory.versionApi(settings)
.version
.enqueue(Callback.callInUI(this, callback, errorCallback))
}
private fun runWithPostNotificationsPermission(action: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// Android 13 and above
val quickPermissionsOption = QuickPermissionsOptions(
handleRationale = true,
handlePermanentlyDenied = true,
preRationaleAction = { stopSlashScreen() },
rationaleMethod = { req -> processPermissionRationale(req) },
permissionsDeniedMethod = { req -> processPermissionRationale(req) },
permanentDeniedMethod = { req -> processPermissionsPermanentDenied(req) }
)
runWithPermissions(
Manifest.permission.POST_NOTIFICATIONS,
options = quickPermissionsOption,
callback = action
)
} else {
// Android 12 and below
action()
}
}
private fun stopSlashScreen() {
splashScreenActive = false
setContentView(R.layout.splash)
}
private fun processPermissionRationale(req: QuickPermissionsRequest) {
MaterialAlertDialogBuilder(this)
.setMessage(getString(R.string.permissions_notification_denied_temp))
.setPositiveButton(getString(R.string.permissions_dialog_grant)) { _, _ ->
req.proceed()
}
.setCancelable(false)
.show()
}
private fun processPermissionsPermanentDenied(req: QuickPermissionsRequest) {
MaterialAlertDialogBuilder(this)
.setMessage(getString(R.string.permissions_notification_denied_permanent))
.setPositiveButton(getString(R.string.permissions_dialog_grant)) { _, _ ->
req.openAppSettings()
}
.setCancelable(false)
.show()
}
}