api calls maintaining for molbio

This commit is contained in:
Mariya
2024-03-02 15:41:17 +05:30
parent 210c9fed5d
commit c8d5d41c81
2 changed files with 74 additions and 40 deletions

View File

@@ -7,6 +7,7 @@ import android.content.DialogInterface
import android.content.Intent import android.content.Intent
import android.content.SharedPreferences import android.content.SharedPreferences
import android.os.BatteryManager import android.os.BatteryManager
import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.util.Base64 import android.util.Base64
import android.util.Log import android.util.Log
@@ -14,6 +15,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.Toast import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
@@ -88,6 +90,7 @@ class HomeFragment : Fragment() {
return binding.root return binding.root
} }
@RequiresApi(Build.VERSION_CODES.P)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
@@ -135,6 +138,7 @@ class HomeFragment : Fragment() {
checkForTokenAndUpdate() checkForTokenAndUpdate()
} }
// Now re-subscribe to allUserData
hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { originalUserDataList -> hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { originalUserDataList ->
Log.d("LOCAL_DB OBSERVE", "OBSERVE CALLED") Log.d("LOCAL_DB OBSERVE", "OBSERVE CALLED")
@@ -186,7 +190,7 @@ class HomeFragment : Fragment() {
} }
// Upload results after processing all userData to avoid duplicates and ensure all modifications are done // Upload results after processing all userData to avoid duplicates and ensure all modifications are done
if (resultList.results?.isNotEmpty() == true) { if (resultList.results?.isNotEmpty() == true) {
hemoCubeViewModel.uploadResultfornew(resultList) hemoCubeViewModel.uploadResult(resultList)
} }
} }
@@ -262,13 +266,16 @@ class HomeFragment : Fragment() {
} }
@RequiresApi(Build.VERSION_CODES.P)
private fun checkForTokenAndUpdate() { private fun checkForTokenAndUpdate() {
var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString()
var password = sharedPreference.getString(Constants.DEVICE_PASSWORD_API, "").toString() var password = sharedPreference.getString(Constants.DEVICE_PASSWORD_API, "").toString()
var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString() var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString()
deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString()
if(userID.isNotEmpty() && password.isNotEmpty()) { if(userID.isNotEmpty() && password.isNotEmpty()) {
Log.d("istoken",isTokenAvailable.toString())
if (!isTokenAvailable) { if (!isTokenAvailable) {
Log.d("istoken1",isTokenAvailable.toString())
if(isTokenExpired(accessToken)) { if(isTokenExpired(accessToken)) {
hemoCubeViewModel.login(createLoginRequestData(userID, password)) hemoCubeViewModel.login(createLoginRequestData(userID, password))
} }
@@ -279,6 +286,14 @@ class HomeFragment : Fragment() {
} }
} else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) {
fetchDeviceCredentials() fetchDeviceCredentials()
var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString()
var userID = sharedPreference.getString("username", "").toString()
var password = sharedPreference.getString("password", "").toString()
if(accessToken.isNotEmpty()){
isTokenAvailable = true
hemoCubeViewModel.startPeriodicCheckUpdate()
hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData())
}
} else { } else {
Toast.makeText( Toast.makeText(
requireContext(), requireContext(),
@@ -293,6 +308,7 @@ class HomeFragment : Fragment() {
updateTokens(response) updateTokens(response)
response.data.data?.accessToken response.data.data?.accessToken
isTokenAvailable = true isTokenAvailable = true
Log.d("istoken2",isTokenAvailable.toString())
} }
is Result.Error -> { is Result.Error -> {
@@ -349,9 +365,30 @@ class HomeFragment : Fragment() {
is Result.Success -> { is Result.Success -> {
val updatedversion = response.data.data?.version.toString() val updatedversion = response.data.data?.version.toString()
val currentversion = val currentversion =
context?.let { context?.packageManager!!.getPackageInfo(it.packageName, 0) } context?.let { ctx ->
val packageInfo = ctx.packageManager.getPackageInfo(ctx.packageName, 0)
val versionName = packageInfo.versionName
val versionCode: Long = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// From Android P (API level 28), versionCode is deprecated and you should use longVersionCode instead.
packageInfo.longVersionCode
} else {
// For older Android versions, use versionCode (cast it to Long for consistency).
packageInfo.versionCode.toLong()
}
// Use versionName and versionCode as needed
Log.d("AppInfo", "Version Name: $versionName, Version Code: $versionCode")
}
Log.d("versionnow",currentversion.toString())
Log.d("versionnow",updatedversion.toString())
if(updatedversion > currentversion.toString()){ if(updatedversion > currentversion.toString()){
hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData())
Toast.makeText(
activity,
"new version ${response.data.data?.version} Available",
Toast.LENGTH_LONG
)
.show()
}else{ }else{
Toast.makeText( Toast.makeText(
activity, activity,
@@ -360,24 +397,17 @@ class HomeFragment : Fragment() {
) )
.show() .show()
} }
Toast.makeText(
activity,
"new version ${response.data.data?.version} Available",
Toast.LENGTH_LONG
)
.show()
} }
is Result.Error -> { is Result.Error -> {
response.exception.let { message -> // response.exception.let { message ->
// Toast.makeText( //// Toast.makeText(
// activity, //// activity,
// "$message", //// "$message",
// Toast.LENGTH_LONG //// Toast.LENGTH_LONG
// ) //// )
// .show() //// .show()
} // }
} }
is Result.Loading -> { is Result.Loading -> {
@@ -459,14 +489,18 @@ class HomeFragment : Fragment() {
private fun isTokenExpired(token: String): Boolean { private fun isTokenExpired(token: String): Boolean {
val parts = token.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if(token.isNotEmpty()) {
val decodedPayload = String(Base64.decode(parts[1], Base64.DEFAULT)) val parts = token.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val jsonPayload = JSONObject(decodedPayload) val decodedPayload = String(Base64.decode(parts[1], Base64.DEFAULT))
val jsonPayload = JSONObject(decodedPayload)
val exp = jsonPayload.optLong("exp", 0) val exp = jsonPayload.optLong("exp", 0)
val currentTimeSeconds = System.currentTimeMillis() / 1000 val currentTimeSeconds = System.currentTimeMillis() / 1000
return exp <= currentTimeSeconds return exp <= currentTimeSeconds
}else{
return false
}
} }
private fun updateTokens(response: Result.Success<LoginResponse>) { private fun updateTokens(response: Result.Success<LoginResponse>) {
@@ -479,6 +513,7 @@ class HomeFragment : Fragment() {
apply() apply()
} }
isTokenAvailable = true isTokenAvailable = true
Log.d("istoken3",isTokenAvailable.toString())
} }
private fun createLoginRequestData(userID: String, password: String): LoginRequest { private fun createLoginRequestData(userID: String, password: String): LoginRequest {
@@ -620,7 +655,11 @@ class HomeFragment : Fragment() {
putString(Constants.NATS_TOKEN, natsToken) putString(Constants.NATS_TOKEN, natsToken)
apply() apply()
} }
hemoCubeViewModel.login(createLoginRequestData(username, password)) if (!isTokenAvailable ) {
Log.d("istoken1", isTokenAvailable.toString())
hemoCubeViewModel.login(createLoginRequestData(username, password))
}
} ?: Log.e("fetchDeviceCredentials", "Failed to parse device data.") } ?: Log.e("fetchDeviceCredentials", "Failed to parse device data.")
} else { } else {
Log.e("fetchDeviceCredentials", "Document does not exist.") Log.e("fetchDeviceCredentials", "Document does not exist.")

View File

@@ -131,29 +131,24 @@ open class HemocubeActivity : AppCompatActivity() {
} }
@RequiresApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("UnspecifiedImmutableFlag") @SuppressLint("MutableImplicitPendingIntent")
private fun requestUserPermission(manager: UsbManager, device: UsbDevice) { private fun requestUserPermission(manager: UsbManager, device: UsbDevice) {
val mPendingIntent: PendingIntent val mPendingIntent: PendingIntent
val pendingIntentFlags = when { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { mPendingIntent = PendingIntent.getBroadcast(
PendingIntent.FLAG_IMMUTABLE this, 0, Intent(Constants.HEMOCUBE_USB_PERMISSION), PendingIntent.FLAG_MUTABLE
} )
else -> { } else {
mPendingIntent = PendingIntent.getBroadcast(
this,
0,
Intent(Constants.HEMOCUBE_USB_PERMISSION),
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
} )
} }
mPendingIntent = PendingIntent.getBroadcast(
this,
0,
Intent(Constants.HEMOCUBE_USB_PERMISSION),
pendingIntentFlags
)
val filter = IntentFilter(Constants.HEMOCUBE_USB_PERMISSION) val filter = IntentFilter(Constants.HEMOCUBE_USB_PERMISSION)
registerReceiver(broadcastReceiver, filter, RECEIVER_EXPORTED) registerReceiver(broadcastReceiver, filter, RECEIVER_EXPORTED)
// Request permission
manager.requestPermission(device, mPendingIntent) manager.requestPermission(device, mPendingIntent)
} }