Skip to content

Commit 94b5859

Browse files
committed
Refactor the login code to send FCM token
1 parent 06f5f30 commit 94b5859

File tree

4 files changed

+46
-46
lines changed

4 files changed

+46
-46
lines changed

android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,15 +98,15 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
9898

9999
if (Settings.isLoggedIn(this)) {
100100
Timber.d("updating SIM1 phone with new fcm token")
101-
val phone = HttpSmsApiService.create(this).updatePhone(Settings.getSIM1PhoneNumber(this), token, Constants.SIM1)
102-
if (phone != null) {
103-
Settings.setUserID(this, phone.userID)
101+
val response = HttpSmsApiService.create(this).updateFcmToken(Settings.getSIM1PhoneNumber(this), Constants.SIM1, token)
102+
if (response.first != null) {
103+
Settings.setUserID(this, response.first!!.userID)
104104
}
105105
}
106106

107107
if(Settings.isDualSIM(this)) {
108108
Timber.d("updating SIM2 phone with new fcm token")
109-
HttpSmsApiService.create(this).updatePhone(Settings.getSIM2PhoneNumber(this), token, Constants.SIM2)
109+
HttpSmsApiService.create(this).updateFcmToken(Settings.getSIM2PhoneNumber(this), Constants.SIM2, token)
110110
}
111111
}
112112

android/app/src/main/java/com/httpsms/HttpSmsApiService.kt

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
129129
return true
130130
}
131131

132-
fun storeHeartbeat(phoneNumbers: Array<String>, charging: Boolean) {
132+
fun storeHeartbeat(phoneNumbers: Array<String>, charging: Boolean): Boolean {
133133
val body = """
134134
{
135135
"charging": $charging,
@@ -148,11 +148,12 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
148148
if (!response.isSuccessful) {
149149
Timber.e("error response [${response.body?.string()}] with code [${response.code}] while sending heartbeat [$body] for phone numbers [${phoneNumbers.joinToString()}]")
150150
response.close()
151-
return
151+
return false
152152
}
153153

154154
response.close()
155155
Timber.i( "heartbeat stored successfully for phone numbers [${phoneNumbers.joinToString()}]" )
156+
return true
156157
}
157158

158159

@@ -195,8 +196,7 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
195196
return true
196197
}
197198

198-
199-
fun updatePhone(phoneNumber: String, fcmToken: String, sim: String): Phone? {
199+
fun updateFcmToken(phoneNumber: String, sim: String, fcmToken: String): Triple<Phone?, String?, String?> {
200200
val body = """
201201
{
202202
"fcm_token": "$fcmToken",
@@ -206,47 +206,27 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
206206
""".trimIndent()
207207

208208
val request: Request = Request.Builder()
209-
.url(resolveURL("/v1/phones"))
209+
.url(resolveURL("/v1/phones/fcm-token"))
210210
.put(body.toRequestBody(jsonMediaType))
211211
.header(apiKeyHeader, apiKey)
212212
.header(clientVersionHeader, BuildConfig.VERSION_NAME)
213213
.build()
214214

215-
val response = client.newCall(request).execute()
216-
if (!response.isSuccessful) {
217-
Timber.e("error response [${response.body?.string()}] with code [${response.code}] while sending fcm token [${body}]")
218-
response.close()
219-
return null
220-
}
221-
222-
val payload = ResponsePhone.fromJson(response.body!!.string())?.data
223-
response.close()
224-
Timber.i("fcm token sent successfully for phone [$phoneNumber] and id [${payload?.id}]" )
225-
return payload
226-
}
227-
228-
229-
fun validateApiKey(): Pair<String?, String?> {
230-
val request: Request = Request.Builder()
231-
.url(resolveURL("/v1/users/me"))
232-
.header(apiKeyHeader, apiKey)
233-
.header(clientVersionHeader, BuildConfig.VERSION_NAME)
234-
.get()
235-
.build()
236-
237215
try {
238216
val response = client.newCall(request).execute()
239217
if (!response.isSuccessful) {
240-
Timber.e("error response [${response.body?.string()}] with code [${response.code}] while verifying apiKey [$apiKey]")
218+
Timber.e("error response [${response.body?.string()}] with code [${response.code}] while updating FCM token [$fcmToken] with apiKey [$apiKey]")
241219
response.close()
242-
return Pair("Cannot validate the API key. Check if it is correct and try again.", null)
220+
return Triple(null,"Cannot validate the API key. Check if it is correct and try again.", null)
243221
}
244222

245223
response.close()
246-
Timber.i("api key [$apiKey] and server url [$baseURL] are valid" )
247-
return Pair(null, null)
224+
Timber.i("FCM token submitted correctly with API key [$apiKey] and server url [$baseURL]" )
225+
226+
val payload = ResponsePhone.fromJson(response.body!!.string())?.data
227+
return Triple(payload, null, null)
248228
} catch (ex: Exception) {
249-
return Pair(null, ex.message)
229+
return Triple(null, null, ex.message)
250230
}
251231
}
252232

android/app/src/main/java/com/httpsms/LoginActivity.kt

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,12 +180,18 @@ class LoginActivity : AppCompatActivity() {
180180
Timber.d("login button clicked")
181181

182182
val error = isGooglePlayServicesAvailable()
183-
if (error != null) {
183+
if (error != null || Settings.getFcmToken(this) == null) {
184184
Timber.d("google play services not installed [${error}]")
185185
Toast.makeText(this, error, Toast.LENGTH_SHORT).show()
186186
return
187187
}
188188

189+
if (Settings.getFcmToken(this) == null) {
190+
Timber.d("The FCM token is not set")
191+
Toast.makeText(this, "Cannot find FCM token. Make sure you have google play services installed", Toast.LENGTH_LONG).show()
192+
return
193+
}
194+
189195
loginButton().isEnabled = false
190196
val progressBar = findViewById<LinearProgressIndicator>(R.id.loginProgressIndicator)
191197
progressBar.visibility = View.VISIBLE
@@ -292,8 +298,20 @@ class LoginActivity : AppCompatActivity() {
292298
}
293299

294300
Thread {
295-
val response = HttpSmsApiService(apiKey.text.toString(), URI(serverUrl.text.toString().trim())).validateApiKey()
296-
liveData.postValue(response)
301+
val service = HttpSmsApiService(apiKey.text.toString(), URI(serverUrl.text.toString().trim()))
302+
303+
var e164PhoneNumber = formatE164(phoneNumber.text.toString().trim())
304+
var response = service.updateFcmToken(e164PhoneNumber, Constants.SIM1, Settings.getFcmToken(this) ?: "")
305+
if(response.second != null || response.third != null || !SmsManagerService.isDualSIM(this)) {
306+
Timber.e("error updating fcm token [${response.second}]")
307+
liveData.postValue(Pair(response.second, response.third))
308+
return@Thread
309+
}
310+
311+
e164PhoneNumber = formatE164(phoneNumberSIM2.text.toString().trim())
312+
response = service.updateFcmToken(e164PhoneNumber, Constants.SIM2, Settings.getFcmToken(this) ?: "")
313+
314+
liveData.postValue(Pair(response.second, response.third))
297315
Timber.d("finished validating api URL")
298316
}.start()
299317
}

android/app/src/main/java/com/httpsms/MainActivity.kt

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import androidx.appcompat.app.AppCompatActivity
2020
import androidx.lifecycle.MutableLiveData
2121
import androidx.work.Constraints
2222
import androidx.work.ExistingPeriodicWorkPolicy
23-
import androidx.work.ListenableWorker.Result
2423
import androidx.work.NetworkType
2524
import androidx.work.PeriodicWorkRequestBuilder
2625
import androidx.work.WorkManager
@@ -203,9 +202,9 @@ class MainActivity : AppCompatActivity() {
203202

204203
private fun sendFCMToken(timestamp: Long, context:Context, phoneNumber: String, sim: String) {
205204
Thread {
206-
val phone = HttpSmsApiService.create(context).updatePhone(phoneNumber, Settings.getFcmToken(context) ?: "", sim)
207-
if (phone != null) {
208-
Settings.setUserID(context, phone.userID)
205+
val response = HttpSmsApiService.create(context).updateFcmToken(phoneNumber, sim,Settings.getFcmToken(context) ?: "")
206+
if (response.first != null) {
207+
Settings.setUserID(context, response.first!!.userID)
209208
Settings.setFcmTokenLastUpdateTimestampAsync(context, timestamp)
210209
Timber.i("[${sim}] FCM token uploaded successfully")
211210
return@Thread
@@ -318,10 +317,10 @@ class MainActivity : AppCompatActivity() {
318317

319318
if (exception != null) {
320319
Timber.w("heartbeat sending failed with [$exception]")
321-
Toast.makeText(context, exception, Toast.LENGTH_SHORT).show()
320+
Toast.makeText(context, exception, Toast.LENGTH_LONG).show()
322321
return@run
323322
}
324-
Toast.makeText(context, "Heartbeat Sent", Toast.LENGTH_SHORT).show()
323+
Toast.makeText(context, "Heartbeat sent successfully", Toast.LENGTH_SHORT).show()
325324

326325
setLastHeartbeatTimestamp(this)
327326
}
@@ -337,7 +336,10 @@ class MainActivity : AppCompatActivity() {
337336
phoneNumbers.add(Settings.getSIM2PhoneNumber(applicationContext))
338337
}
339338
Timber.w("numbers = [${phoneNumbers.joinToString()}]")
340-
HttpSmsApiService.create(context).storeHeartbeat(phoneNumbers.toTypedArray(), charging)
339+
val isStored = HttpSmsApiService.create(context).storeHeartbeat(phoneNumbers.toTypedArray(), charging)
340+
if (!isStored) {
341+
error = "Could not send heartbeat make sure the phone is connected to the internet"
342+
}
341343
Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())
342344
} catch (exception: Exception) {
343345
Timber.e(exception)

0 commit comments

Comments
 (0)