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
241 lines (205 loc) · 8.44 KB
/
MainActivity.kt
File metadata and controls
241 lines (205 loc) · 8.44 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
package com.httpsms
import android.Manifest
import android.Manifest.permission.READ_PHONE_NUMBERS
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.telephony.PhoneNumberUtils
import android.telephony.TelephonyManager
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.material.button.MaterialButton
import com.google.android.material.switchmaterial.SwitchMaterial
import com.httpsms.services.StickyNotificationService
import timber.log.Timber
import java.util.*
class MainActivity : AppCompatActivity() {
private val sentReceiver = SentReceiver()
private val deliveredReceiver = DeliveredReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initTimber()
redirectToLogin()
setContentView(R.layout.activity_main)
createChannel()
requestPermissions(this)
setOwner(getPhoneNumber(this))
setActiveStatus(this)
registerListeners()
refreshToken(this)
startStickyNotification(this)
}
override fun onResume() {
super.onResume()
Timber.d( "on activity resume")
redirectToLogin()
refreshToken(this)
}
private fun startStickyNotification(context: Context) {
Timber.d("starting foreground service")
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
}
Thread {
val updated = HttpSmsApiService(Settings.getApiKeyOrDefault(context))
.updatePhone(Settings.getOwnerOrDefault(context), Settings.getFcmToken(context) ?: "")
if (updated) {
Settings.setFcmTokenLastUpdateTimestampAsync(context, currentTimeStamp)
Timber.i("fcm token uploaded successfully")
return@Thread
}
Timber.e("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 (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
Timber.plant(LogtailTree())
}
}
private fun registerListeners() {
findViewById<MaterialButton>(R.id.mainLogoutButton).setOnClickListener { onLogoutClick() }
}
private fun onLogoutClick() {
Timber.d("logout button clicked")
Settings.setApiKeyAsync(this, null)
Settings.setOwnerAsync(this, null)
Settings.setFcmTokenLastUpdateTimestampAsync(this, 0)
redirectToLogin()
}
private fun redirectToLogin():Boolean {
if (Settings.isLoggedIn(this)) {
return false
}
val switchActivityIntent = Intent(this, LoginActivity::class.java)
startActivity(switchActivityIntent)
return true
}
private fun setActiveStatus(context: Context) {
val switch = findViewById<SwitchMaterial>(R.id.cardSwitch)
switch.isChecked = Settings.getActiveStatus(context)
switch.setOnCheckedChangeListener{
_, isChecked ->
run {
if (isChecked && !hasAllPermissions(context)) {
Toast.makeText(context, "PERMISSIONS_NOT_GRANTED", Toast.LENGTH_SHORT).show()
} else {
Settings.setActiveStatusAsync(context, isChecked)
}
}
}
}
private fun hasAllPermissions(context: Context): Boolean {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.SEND_SMS
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
READ_PHONE_NUMBERS
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
Manifest.permission.RECEIVE_SMS
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED
) {
return true
}
return false
}
private fun setOwner(phoneNumber: String) {
val titleText = findViewById<TextView>(R.id.cardPhoneNumber)
titleText.text = PhoneNumberUtils.formatNumber(phoneNumber, Locale.getDefault().country)
}
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("HardwareIds")
private fun getPhoneNumber(context: Context): String {
val telephonyManager = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_SMS
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
READ_PHONE_NUMBERS
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_PHONE_STATE
) != PackageManager.PERMISSION_GRANTED
) {
Timber.d("cannot get owner because permissions are not granted")
return Settings.getOwnerOrDefault(this)
}
if (telephonyManager.line1Number != null && telephonyManager.line1Number != "") {
Timber.d("line 1 number fetched [${telephonyManager.line1Number}]")
Settings.setOwnerAsync(context, telephonyManager.line1Number)
}
return Settings.getOwnerOrDefault(this)
}
private fun requestPermissions(context:Context) {
if(!Settings.isLoggedIn(context)) {
return
}
Timber.d("requesting permissions")
val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
permissions.entries.forEach {
Timber.d("${it.key} = ${it.value}")
setOwner(getPhoneNumber(context))
}
}
requestPermissionLauncher.launch(
arrayOf(
Manifest.permission.SEND_SMS,
Manifest.permission.RECEIVE_SMS,
READ_PHONE_NUMBERS,
Manifest.permission.READ_SMS,
Manifest.permission.READ_PHONE_STATE
)
)
Timber.d("creating permissions launcher")
}
}