forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainActivity.kt
More file actions
353 lines (297 loc) · 13.4 KB
/
MainActivity.kt
File metadata and controls
353 lines (297 loc) · 13.4 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package com.httpsms
import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.telephony.PhoneNumberUtils
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.httpsms.services.StickyNotificationService
import com.httpsms.worker.HeartbeatWorker
import okhttp3.internal.format
import timber.log.Timber
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit
import android.provider.Settings as ProviderSettings
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initTimber()
redirectToLogin()
setContentView(R.layout.activity_main)
createChannel()
setCardContent(this)
registerListeners()
refreshToken(this)
startStickyNotification(this)
scheduleHeartbeatWorker(this)
setVersion()
setHeartbeatListener(this)
setBatteryOptimizationListener()
}
override fun onStart() {
super.onStart()
requestPermissions(this)
}
override fun onResume() {
super.onResume()
Timber.d( "on activity resume")
redirectToLogin()
refreshToken(this)
setCardContent(this)
setBatteryOptimizationListener()
}
private fun setVersion() {
val appVersionView = findViewById<TextView>(R.id.mainAppVersion)
appVersionView.text = format(getString(R.string.app_version), BuildConfig.VERSION_NAME)
}
private fun setCardContent(context: Context) {
val titleText = findViewById<TextView>(R.id.cardPhoneNumber)
titleText.text = PhoneNumberUtils.formatNumber(Settings.getSIM1PhoneNumber(this), Locale.getDefault().country)
if(!Settings.getActiveStatus(context, Constants.SIM1)) {
titleText.setCompoundDrawables(null, null, null, null)
}
val titleTextSIM2 = findViewById<TextView>(R.id.cardPhoneNumberSIM2)
titleTextSIM2.text = PhoneNumberUtils.formatNumber(Settings.getSIM2PhoneNumber(this), Locale.getDefault().country)
if(!Settings.getActiveStatus(context, Constants.SIM2)) {
titleTextSIM2.setCompoundDrawables(null, null, null, null)
}
setLastHeartbeatTimestamp(context)
if(!Settings.isDualSIM(context)) {
val sim2Card = findViewById<MaterialCardView>(R.id.mainPhoneCardSIM2)
sim2Card.visibility = MaterialCardView.GONE
}
}
private fun requestPermissions(context:Context) {
Timber.d("requesting permissions")
val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
permissions.entries.forEach {
Timber.d("${it.key} = ${it.value}")
if (it.key == Manifest.permission.READ_CALL_LOG && !it.value) {
Timber.w("disabling incoming call events since for SIM1 and SIM2")
Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, false)
Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, false)
}
}
}
var permissions = arrayOf(
Manifest.permission.SEND_SMS,
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS
)
if(Build.VERSION.SDK_INT >= 33) {
permissions += Manifest.permission.POST_NOTIFICATIONS
}
if(Settings.isIncomingCallEventsEnabled(context,Constants.SIM1) || Settings.isIncomingCallEventsEnabled(context,Constants.SIM2) ) {
permissions += Manifest.permission.READ_CALL_LOG
permissions += Manifest.permission.READ_PHONE_STATE
}
requestPermissionLauncher.launch(permissions)
Timber.d("creating permissions launcher")
}
private fun scheduleHeartbeatWorker(context: Context) {
val tag = "TAG_HEARTBEAT_WORKER"
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val heartbeatWorker =
PeriodicWorkRequestBuilder<HeartbeatWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.addTag(tag)
.build()
WorkManager
.getInstance(context)
.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP, heartbeatWorker)
Timber.d("finished scheduling heartbeat worker with ID [${heartbeatWorker.id}]")
}
private fun startStickyNotification(context: Context) {
Timber.d("starting foreground service")
if(!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) {
Timber.d("active status is false, not starting foreground service")
return
}
val notificationIntent = Intent(context, StickyNotificationService::class.java)
val service = context.startForegroundService(notificationIntent)
Timber.d("foreground service started [${service?.className}]")
}
private fun refreshToken(context: Context) {
if(!Settings.isLoggedIn(context)) {
Timber.w("cannot refresh token because owner is not logged in")
return
}
if(!Settings.hasOwner(context)) {
Timber.w("cannot refresh token because owner does not exist")
return
}
if (Settings.getFcmToken(context) == null) {
Timber.w("cannot refresh token because token does not exist")
return
}
val updateTimestamp = Settings.getFcmTokenLastUpdateTimestamp(context)
Timber.d("FCM_TOKEN_UPDATE_TIMESTAMP: $updateTimestamp")
val interval = 24 * 60 * 60 * 1000 // 1 day
val currentTimeStamp = System.currentTimeMillis()
if (currentTimeStamp - updateTimestamp < interval) {
Timber.i("update interval [${currentTimeStamp - updateTimestamp}] < 24 hours [$interval]")
return
}
sendFCMToken(currentTimeStamp, context, Settings.getSIM1PhoneNumber(context), Constants.SIM1)
if (Settings.isDualSIM(context)) {
sendFCMToken(currentTimeStamp, context, Settings.getSIM2PhoneNumber(context), Constants.SIM2)
}
}
private fun sendFCMToken(timestamp: Long, context:Context, phoneNumber: String, sim: String) {
Thread {
val phone = HttpSmsApiService.create(context).updatePhone(phoneNumber, Settings.getFcmToken(context) ?: "", sim)
if (phone != null) {
Settings.setUserID(context, phone.userID)
Settings.setFcmTokenLastUpdateTimestampAsync(context, timestamp)
Timber.i("[${sim}] FCM token uploaded successfully")
return@Thread
} else {
Timber.e("[${sim}] could not update FCM token")
}
}.start()
}
private fun initTimber() {
if (Timber.treeCount > 1) {
Timber.d("timber is already initialized with count [${Timber.treeCount}]")
return
}
if(Settings.isDebugLogEnabled(this)) {
Timber.plant(Timber.DebugTree())
Timber.plant(LogzTree(this.applicationContext))
}
}
private fun registerListeners() {
findViewById<MaterialButton>(R.id.mainSettingsButton).setOnClickListener { onSettingsClick() }
}
private fun onSettingsClick() {
Timber.d("settings button clicked")
val switchActivityIntent = Intent(this, SettingsActivity::class.java)
startActivity(switchActivityIntent)
}
private fun redirectToLogin():Boolean {
if (Settings.isLoggedIn(this)) {
return false
}
val switchActivityIntent = Intent(this, LoginActivity::class.java)
startActivity(switchActivityIntent)
return true
}
private fun setLastHeartbeatTimestamp(context: Context) {
val refreshTimestampView = findViewById<TextView>(R.id.cardRefreshTime)
val timestamp = Settings.getHeartbeatTimestamp(context)
if (timestamp == 0.toLong()) {
Timber.d("no heartbeat timestamp has been set")
refreshTimestampView.text = "--"
return
}
val timestampZdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC)
val localTime = timestampZdt.withZoneSameInstant(ZoneId.systemDefault())
Timber.d("heartbeat timestamp in UTC is [${timestampZdt}] and local is [$localTime]")
refreshTimestampView.text = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
if (Settings.isDualSIM(context)) {
val refreshTimestampViewSIM2 = findViewById<TextView>(R.id.cardRefreshTimeSIM2)
refreshTimestampViewSIM2.text = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
}
}
private fun createChannel() {
// Create the NotificationChannel
val name = getString(R.string.notification_channel_default)
val descriptionText = getString(R.string.notification_channel_default)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(name, name, importance)
mChannel.description = descriptionText
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
@SuppressLint("BatteryLife")
private fun setBatteryOptimizationListener() {
val pm = getSystemService(POWER_SERVICE) as PowerManager
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
val button = findViewById<MaterialButton>(R.id.batteryOptimizationButtonButton)
button.setOnClickListener {
val intent = Intent()
intent.action = ProviderSettings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:$packageName")
startActivity(intent)
}
} else {
val layout = findViewById<LinearLayout>(R.id.batteryOptimizationLinearLayout)
layout.visibility = View.GONE
}
}
private fun setHeartbeatListener(context: Context) {
findViewById<MaterialButton>(R.id.mainHeartbeatButton).setOnClickListener{onHeartbeatClick(context)}
}
private fun onHeartbeatClick(context: Context) {
Timber.d("heartbeat button clicked")
val heartbeatButton = findViewById<MaterialButton>(R.id.mainHeartbeatButton)
heartbeatButton.isEnabled = false
val progressBar = findViewById<LinearProgressIndicator>(R.id.mainProgressIndicator)
progressBar.visibility = View.VISIBLE
val liveData = MutableLiveData<String?>()
liveData.observe(this) { exception ->
run {
progressBar.visibility = View.INVISIBLE
heartbeatButton.isEnabled = true
if (exception != null) {
Timber.w("heartbeat sending failed with [$exception]")
Toast.makeText(context, exception, Toast.LENGTH_SHORT).show()
return@run
}
Toast.makeText(context, "Heartbeat Sent", Toast.LENGTH_SHORT).show()
setLastHeartbeatTimestamp(this)
}
}
Thread {
val charging = Settings.isCharging(applicationContext)
var error: String? = null
try {
HttpSmsApiService.create(context).storeHeartbeat(Settings.getSIM1PhoneNumber(context), charging)
Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())
} catch (exception: Exception) {
Timber.e(exception)
error = exception.javaClass.simpleName
}
if (Settings.isDualSIM(context)) {
try {
HttpSmsApiService.create(context).storeHeartbeat(Settings.getSIM2PhoneNumber(context), charging)
Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())
} catch (exception: Exception) {
Timber.e(exception)
error = exception.javaClass.simpleName
}
}
liveData.postValue(error)
Timber.d("finished sending pulse")
}.start()
}
}