From bb6f4ee85955fdacab92eb6c3bd6f7b59b5addd8 Mon Sep 17 00:00:00 2001 From: Mariya Date: Tue, 27 Feb 2024 12:42:30 +0530 Subject: [PATCH 01/14] Apk Update Code Added --- .../hpostesting/data/constant/Constants.kt | 2 +- .../hpostesting/presentation/NatsManager.kt | 2 +- .../dashboard/DashboardActivity.kt | 110 +++++++++--------- build.gradle | 2 +- 4 files changed, 55 insertions(+), 61 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt b/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt index 99a20e8..e2896ee 100644 --- a/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt +++ b/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt @@ -8,7 +8,7 @@ object Constants { const val ABHA_APP_PACKAGE = "in.ndhm.phr" - const val MOLBIO_INTEGRATION = false + const val MOLBIO_INTEGRATION = true const val deviceProvisionEmail = "HPOS_provisioner@bigtec.co.in" const val deviceProvisionPassword = "f2ab0e7f9d69" const val DEVICE_ID_API = "deviceIDAPI" diff --git a/app/src/main/java/com/example/hpostesting/presentation/NatsManager.kt b/app/src/main/java/com/example/hpostesting/presentation/NatsManager.kt index 36cd967..8f2eaf3 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/NatsManager.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/NatsManager.kt @@ -172,7 +172,7 @@ class NatsManager(datacollector: DashboardActivity) { println("Message received (up to 100 times): $response") } - d?.subscribe("device.hpos.${deviceId}.checkupdate") { msg -> + d?.subscribe("device.hpos.${deviceId}.checkUpdate") { msg -> val response = String(msg.data, StandardCharsets.UTF_8) datacollector.setResponse(response) println("Message received (up to 100 times): $response") diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index 4bcb859..f8b2f98 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt @@ -1,7 +1,5 @@ package com.example.hpostesting.presentation.dashboard -import android.app.DownloadManager -import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.SharedPreferences @@ -23,6 +21,7 @@ import androidx.navigation.ui.setupWithNavController import com.example.hpostesting.data.Result import com.example.hpostesting.data.constant.Constants import com.example.hpostesting.data.constant.LanguageManager +import com.example.hpostesting.data.model.updates.DeviceUpdateRequest import com.example.hpostesting.presentation.NatsManager import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel import com.example.hpostesting.presentation.jig.JigActivity @@ -35,6 +34,8 @@ import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.ActivityDashboardBinding import okhttp3.ResponseBody import java.io.File +import java.io.FileOutputStream +import java.io.InputStream interface NatsMessageCallback { fun onMessageReceived(topic: String, message: String) @@ -57,7 +58,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { private var downloadId: Long = 0 // TODO: Remove hemocube viewmodel private val hemocubeViewModel: HemoCubeViewModel by viewModels() - + private lateinit var sharedPreference: SharedPreferences override fun attachBaseContext(newBase: Context?) { val languageCode = LanguageManager.getSavedLanguage(newBase!!) LanguageManager.setLocale(newBase, languageCode) @@ -91,14 +92,13 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { is Result.Success -> { // Handle success val apkUrl = result.data -// val apkUrl = "https://dl.dropboxusercontent.com/s/fi/1c3nn7t0co431hicl3hrt/app-debug.apk?rlkey=e4uf13ty1dpcked614vy1aaqp&dl=0" - initiateUpdate(apkUrl.toString()) - Log.d("ApI", "APK URL: $apkUrl") -// Toast.makeText( -// this, -// "APK UPLOAD ${result.data}", -// Toast.LENGTH_SHORT -// ).show() + downloadApk(apkUrl) + Log.e("ApI", "APK URL: $apkUrl") + Toast.makeText( + this, + "${result.data}", + Toast.LENGTH_SHORT + ).show() } is Result.Error -> { @@ -145,69 +145,54 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } - private fun initiateUpdate(responseBody: String) { - val apkUrl = responseBody - if (!isValidHttpUrl(apkUrl)) { - return - } + private fun downloadApk(responseBody: ResponseBody) { + val file = File(getExternalFilesDir(null), "update.apk") + var inputStream: InputStream? = null + var outputStream: FileOutputStream? = null + try { + val fileReader = ByteArray(4096) + val fileSize = responseBody.contentLength() + var fileSizeDownloaded: Long = 0 - val request = DownloadManager.Request(Uri.parse(apkUrl)) - request.setTitle("App Update") - request.setDescription("Downloading update...") - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) - request.setDestinationInExternalFilesDir(this, "Updates", "update.apk") + inputStream = responseBody.byteStream() + outputStream = FileOutputStream(file) - val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager - downloadId = downloadManager.enqueue(request) - - // Register a BroadcastReceiver to receive the download complete event -// val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE) -// registerReceiver(downloadReceiver, filter) - } - private fun extractApkUrl(responseBody: ResponseBody): String { - return responseBody.string() - } - private fun isValidHttpUrl(url: String): Boolean { - return url.startsWith("http://") || url.startsWith("https://") - } - private val downloadReceiver = object : BroadcastReceiver() { - override fun onReceive(context: Context?, intent: Intent?) { - val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) - if (id == downloadId) { - installApk() + while (true) { + val read = inputStream.read(fileReader) + if (read == -1) { + break + } + outputStream.write(fileReader, 0, read) + fileSizeDownloaded += read.toLong() + Log.d(TAG, "File download: $fileSizeDownloaded of $fileSize") } + outputStream.flush() + installApk(file) // Call installApk directly with the file + } catch (e: Exception) { + Log.e(TAG, "Error saving APK: ${e.message}") + } finally { + inputStream?.close() + outputStream?.close() } } - private fun installApk() { - val file = File(getExternalFilesDir("Updates"), "update.apk") - file.setReadable(true, false) // Ensure the file is readable - - val pInfo = baseContext.packageManager.getPackageInfo(baseContext.packageName, 0) + private fun installApk(file: File) { val uri: Uri = FileProvider.getUriForFile( this, - "${pInfo}.fileprovider", + "${applicationContext.packageName}.provider", // Update this with your FileProvider authority file ) - // Create an intent to install the APK - val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE) - installIntent.data = uri - installIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_ACTIVITY_NEW_TASK or - Intent.FLAG_ACTIVITY_CLEAR_TOP - installIntent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true) - - // Start the installation + val installIntent = Intent(Intent.ACTION_VIEW).apply { + data = uri + flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or + Intent.FLAG_ACTIVITY_CLEAR_TOP + } startActivity(installIntent) - - Log.d("InstallApk", "Install Intent URI: $uri") - Log.d("InstallApk", "Package Name: $packageName") } override fun onDestroy() { super.onDestroy() -// unregisterReceiver(downloadReceiver) } override fun onResume() { @@ -260,5 +245,14 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { responses = responses+response+"\n" println(responses) + if (response.contains("checkUpdate")) { + hemocubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) + } + } + + private fun createDeviceUpdateRequestData(): DeviceUpdateRequest { + return DeviceUpdateRequest( + serial_no = sharedPreference.getString(Constants.DEVICE_ID, "") + ) } } \ No newline at end of file diff --git a/build.gradle b/build.gradle index b9e66db..ef52576 100644 --- a/build.gradle +++ b/build.gradle @@ -3,7 +3,7 @@ buildscript { kotlin_version = '1.8.21' } dependencies { - classpath 'com.android.tools.build:gradle:8.1.1' + classpath 'com.android.tools.build:gradle:8.2.2' classpath 'com.google.gms:google-services:4.4.0' classpath 'com.google.firebase:firebase-appdistribution-gradle:4.0.1' } From 71d298cd6969e1e91d013ae0cf01291bf37aff9a Mon Sep 17 00:00:00 2001 From: Mariya Date: Tue, 27 Feb 2024 14:59:03 +0530 Subject: [PATCH 02/14] Apk Update Code Added --- .../dashboard/DashboardActivity.kt | 8 ++-- .../presentation/dashboard/HomeFragment.kt | 40 +++++++++++++++++-- app/src/main/res/xml/file_paths.xml | 2 +- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index f8b2f98..58cf01f 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt @@ -146,7 +146,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { } private fun downloadApk(responseBody: ResponseBody) { - val file = File(getExternalFilesDir(null), "update.apk") + val file = File(getExternalFilesDir(null), "Update.apk") var inputStream: InputStream? = null var outputStream: FileOutputStream? = null try { @@ -245,9 +245,9 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { responses = responses+response+"\n" println(responses) - if (response.contains("checkUpdate")) { - hemocubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) - } +// if (response.contains("checkUpdate")) { +// hemocubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) +// } } private fun createDeviceUpdateRequestData(): DeviceUpdateRequest { diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index b71e0d9..9847f44 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -253,11 +253,11 @@ class HomeFragment : Fragment() { hemoCubeViewModel.login(createLoginRequestData(userID, password)) } else { isTokenAvailable = true - - hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) hemoCubeViewModel.uploadLogs() hemoCubeViewModel.startPeriodicCheckUpdate() hemoCubeViewModel.downloadClientCertificate() + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) + } } } else if (deviceId.isNotEmpty()) { @@ -271,9 +271,9 @@ class HomeFragment : Fragment() { } else { // Continue with your existing logic if the token is not empty. isTokenAvailable = true - hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) hemoCubeViewModel.uploadLogs() hemoCubeViewModel.startPeriodicCheckUpdate() + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) } } else { Toast.makeText( @@ -337,6 +337,40 @@ class HomeFragment : Fragment() { } } + hemoCubeViewModel.checkUpdate.observe(viewLifecycleOwner) { response -> + when (response) { + is Result.Success -> { + // Handle success + val apkUrl = response.data + Log.e("ApI", "APK URL: $apkUrl") + hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) + Toast.makeText( + activity, + " ${response.data}", + Toast.LENGTH_LONG + ) + .show() + } + + is Result.Error -> { + response.exception.let { message -> + Toast.makeText( + activity, + "An error occurred in uploading logs: $message", + Toast.LENGTH_LONG + ) + .show() + } + } + + is Result.Loading -> { + } + + else -> { + } + } + } + hemoCubeViewModel.downloadcertificate.observe(viewLifecycleOwner) { response -> when (response) { is Result.Success -> { diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 6e9c380..72a05d1 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -1,3 +1,3 @@ - + From 5cdc156f33746334fbd5b52b7b34ff9288ee194f Mon Sep 17 00:00:00 2001 From: Mariya Date: Tue, 27 Feb 2024 16:49:25 +0530 Subject: [PATCH 03/14] Apk Update Code Added --- app/src/main/AndroidManifest.xml | 1 + .../dashboard/DashboardActivity.kt | 34 +++++++++++++------ app/src/main/res/xml/file_paths.xml | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 +-- 4 files changed, 27 insertions(+), 14 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6a31cea..fdb4286 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -25,6 +25,7 @@ { // Handle success val apkUrl = result.data - downloadApk(apkUrl) + val responseBodyString = apkUrl.string() + + + val fileToWriteTo = File(this.getExternalFilesDir(null), "downloaded_file.apk") + + apkUrl.byteStream().use { inputStream -> + FileOutputStream(fileToWriteTo).use { outputStream -> + inputStream.copyTo(outputStream) + } + } + Log.d(TAG, "Responsebody: $responseBodyString") + installApk(fileToWriteTo) Log.e("ApI", "APK URL: $apkUrl") Toast.makeText( this, @@ -167,7 +179,6 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { Log.d(TAG, "File download: $fileSizeDownloaded of $fileSize") } outputStream.flush() - installApk(file) // Call installApk directly with the file } catch (e: Exception) { Log.e(TAG, "Error saving APK: ${e.message}") } finally { @@ -176,19 +187,20 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { } } - private fun installApk(file: File) { - val uri: Uri = FileProvider.getUriForFile( + private fun installApk(fileToWriteTo: File) { + val apkUri = FileProvider.getUriForFile( this, - "${applicationContext.packageName}.provider", // Update this with your FileProvider authority - file + "${BuildConfig.APPLICATION_ID}.provider", + fileToWriteTo ) - val installIntent = Intent(Intent.ACTION_VIEW).apply { - data = uri - flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_ACTIVITY_CLEAR_TOP + + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(apkUri, "application/vnd.android.package-archive") + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION } - startActivity(installIntent) + startActivity(intent) + } override fun onDestroy() { diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 72a05d1..f6fa670 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -1,3 +1,3 @@ - + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 6c81b1c..2f0e0a2 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Mon Jun 12 17:07:47 IST 2023 +#Tue Feb 27 16:09:58 IST 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From 70b0b93f57576d6ed0b7c01627272c6a80dd0b19 Mon Sep 17 00:00:00 2001 From: Mariya Date: Tue, 27 Feb 2024 20:44:32 +0530 Subject: [PATCH 04/14] Apk Update Code Added --- .../dashboard/DashboardActivity.kt | 46 +++++++++++++++---- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index bae56ac..8937d4b 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt @@ -34,9 +34,12 @@ import `in`.sminnovations.hpostesting.BuildConfig import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.ActivityDashboardBinding import okhttp3.ResponseBody +import java.io.BufferedInputStream import java.io.File +import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream +import java.util.zip.ZipInputStream interface NatsMessageCallback { fun onMessageReceived(topic: String, message: String) @@ -92,20 +95,17 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { when (result) { is Result.Success -> { // Handle success - val apkUrl = result.data - val responseBodyString = apkUrl.string() - - + val apk = result.data val fileToWriteTo = File(this.getExternalFilesDir(null), "downloaded_file.apk") - apkUrl.byteStream().use { inputStream -> - FileOutputStream(fileToWriteTo).use { outputStream -> - inputStream.copyTo(outputStream) + apk.byteStream().use { input -> + fileToWriteTo.outputStream().use { output -> + input.copyTo(output) } } - Log.d(TAG, "Responsebody: $responseBodyString") + Log.d("Responsebodyformat", "Responsebodyformat: ") installApk(fileToWriteTo) - Log.e("ApI", "APK URL: $apkUrl") + Log.e("ApI", "APK URL: $apk") Toast.makeText( this, "${result.data}", @@ -203,6 +203,34 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { } + + fun unzip(zipFilePath: String, outputFolderPath: String) { + ZipInputStream(BufferedInputStream(FileInputStream(zipFilePath))).use { zis -> + var zipEntry = zis.nextEntry + val buffer = ByteArray(1024) + + while (zipEntry != null) { + val fileName = zipEntry.name + val newFile = File(outputFolderPath, fileName) + + if (zipEntry.isDirectory) { + newFile.mkdirs() + } else { + // Create all parent directories + newFile.parent?.let { File(it).mkdirs() } + + FileOutputStream(newFile).use { fos -> + var len: Int + while (zis.read(buffer).also { len = it } > 0) { + fos.write(buffer, 0, len) + } + } + } + zipEntry = zis.nextEntry + } + zis.closeEntry() + } + } override fun onDestroy() { super.onDestroy() } From 626dd380ab49ddc7b60c7254f00c3656828cf5c0 Mon Sep 17 00:00:00 2001 From: Mariya Date: Wed, 28 Feb 2024 14:46:06 +0530 Subject: [PATCH 05/14] Apk update successfully added --- .../dashboard/DashboardActivity.kt | 91 +++++-------------- 1 file changed, 22 insertions(+), 69 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index 8937d4b..009662c 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt @@ -1,5 +1,6 @@ package com.example.hpostesting.presentation.dashboard +import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences @@ -74,6 +75,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { Log.d(TAG, "Received message on topic $topic: $message") } + @SuppressLint("SetWorldReadable") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -96,15 +98,17 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { is Result.Success -> { // Handle success val apk = result.data - val fileToWriteTo = File(this.getExternalFilesDir(null), "downloaded_file.apk") + val file = File(getExternalFilesDir("Updates"), "update.apk") + file.setReadable(true, false) // Ensure the file is readable + apk.byteStream().use { input -> - fileToWriteTo.outputStream().use { output -> + file.outputStream().use { output -> input.copyTo(output) } } Log.d("Responsebodyformat", "Responsebodyformat: ") - installApk(fileToWriteTo) + installApk(file) Log.e("ApI", "APK URL: $apk") Toast.makeText( this, @@ -157,80 +161,29 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } - private fun downloadApk(responseBody: ResponseBody) { - val file = File(getExternalFilesDir(null), "Update.apk") - var inputStream: InputStream? = null - var outputStream: FileOutputStream? = null - try { - val fileReader = ByteArray(4096) - val fileSize = responseBody.contentLength() - var fileSizeDownloaded: Long = 0 - inputStream = responseBody.byteStream() - outputStream = FileOutputStream(file) - - while (true) { - val read = inputStream.read(fileReader) - if (read == -1) { - break - } - outputStream.write(fileReader, 0, read) - fileSizeDownloaded += read.toLong() - Log.d(TAG, "File download: $fileSizeDownloaded of $fileSize") - } - outputStream.flush() - } catch (e: Exception) { - Log.e(TAG, "Error saving APK: ${e.message}") - } finally { - inputStream?.close() - outputStream?.close() - } - } - - private fun installApk(fileToWriteTo: File) { - val apkUri = FileProvider.getUriForFile( + private fun installApk(file: File) { + val pInfo = baseContext.packageManager.getPackageInfo(baseContext.packageName, 0) + val uri: Uri = FileProvider.getUriForFile( this, - "${BuildConfig.APPLICATION_ID}.provider", - fileToWriteTo + "${BuildConfig.APPLICATION_ID}.fileprovider", + file ) + val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE) + installIntent.data = uri + installIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or + Intent.FLAG_ACTIVITY_NEW_TASK or + Intent.FLAG_ACTIVITY_CLEAR_TOP + installIntent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true) - val intent = Intent(Intent.ACTION_VIEW).apply { - setDataAndType(apkUri, "application/vnd.android.package-archive") - flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION - } - startActivity(intent) + // Start the installation + startActivity(installIntent) + Log.d("InstallApk", "Install Intent URI: $uri") + Log.d("InstallApk", "Package Name: $packageName") } - - fun unzip(zipFilePath: String, outputFolderPath: String) { - ZipInputStream(BufferedInputStream(FileInputStream(zipFilePath))).use { zis -> - var zipEntry = zis.nextEntry - val buffer = ByteArray(1024) - - while (zipEntry != null) { - val fileName = zipEntry.name - val newFile = File(outputFolderPath, fileName) - - if (zipEntry.isDirectory) { - newFile.mkdirs() - } else { - // Create all parent directories - newFile.parent?.let { File(it).mkdirs() } - - FileOutputStream(newFile).use { fos -> - var len: Int - while (zis.read(buffer).also { len = it } > 0) { - fos.write(buffer, 0, len) - } - } - } - zipEntry = zis.nextEntry - } - zis.closeEntry() - } - } override fun onDestroy() { super.onDestroy() } From e8b5d12db5c839ed04fbe9d5bad3b4364691f240 Mon Sep 17 00:00:00 2001 From: Mariya Date: Wed, 28 Feb 2024 15:12:21 +0530 Subject: [PATCH 06/14] removed unwanted toast messages --- app/build.gradle | 4 ++-- .../presentation/dashboard/HomeFragment.kt | 20 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index bafb970..1fc3875 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -19,8 +19,8 @@ android { applicationId "in.sminnovations.hpostesting.dev" minSdk 21 targetSdk 34 - versionCode 112 - versionName "2.1.112" + versionCode 117 + versionName "2.1.117" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index 9847f44..ddaabe9 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -379,20 +379,20 @@ class HomeFragment : Fragment() { val fileName = "nats_certificate.zip" val downloadDirectory = "NATS" val file = downloadFile(url, requireContext(), fileName, downloadDirectory) - Toast.makeText( - requireContext(), - "NATS certificate Downloaded", - Toast.LENGTH_SHORT - ).show() +// Toast.makeText( +// requireContext(), +// "NATS certificate Downloaded", +// Toast.LENGTH_SHORT +// ).show() val unzipDirectoryPath = requireContext().getExternalFilesDir(null)?.absolutePath + "/$downloadDirectory" unzip(file.absolutePath, unzipDirectoryPath) - Toast.makeText( - requireContext(), - "NATS certificate Extracted", - Toast.LENGTH_SHORT - ).show() +// Toast.makeText( +// requireContext(), +// "NATS certificate Extracted", +// Toast.LENGTH_SHORT +// ).show() } is Result.Error -> { From f7dc879c75d98005356dc04132db3e75ffd646f9 Mon Sep 17 00:00:00 2001 From: Mariya Date: Wed, 28 Feb 2024 15:17:36 +0530 Subject: [PATCH 07/14] added code related offline bulkupload --- .../presentation/dashboard/HomeFragment.kt | 62 +++++++++++++------ 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index ddaabe9..cee240b 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -135,37 +135,59 @@ class HomeFragment : Fragment() { checkForTokenAndUpdate() } - hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> - val resultList = MolbioV2ResultRequest(mutableListOf(MolbioV2Result())) - userDataList.forEach { userData -> + hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { originalUserDataList -> + + Log.d("LOCAL_DB OBSERVE", "OBSERVE CALLED") + + val resultList = MolbioV2ResultRequest(mutableListOf()) + originalUserDataList.forEach { userData -> + Log.d( + ": USER DATA", + originalUserDataList.count().toString() + " : " + userData._id + ) + if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { + val currentTimeFormatted = SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + Locale.getDefault() + ).format(Calendar.getInstance().time) + val bufferIntensityThreshold = + Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId]?.toString() + ?: "defaultThreshold" // Handle possible nulls safely resultList.results?.add( MolbioV2Result( rawData = userData, analysisId = userData._id, - analysisDate = "2024-02-08 16:33:56",//userData.testTime, - analysisStatus = userData.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), - interpretation = userData.classificationResult, + analysisDate = currentTimeFormatted, + analysisStatus = userData.classificationResult + ?: "defaultStatus", // Handle possible nulls + thresholds = bufferIntensityThreshold, + interpretation = userData.classificationResult + ?: "defaultInterpretation", // Handle possible nulls testId = userData._id, - testTime = "2024-02-08 16:33:56",//userData.testTime, - collectionTime = "2024-02-08 16:33:56",//userData.testTime, - expiryTime = "2024-02-08 16:33:56"//userData.testTime, + testTime = currentTimeFormatted, + collectionTime = currentTimeFormatted, + expiryTime = currentTimeFormatted ) ) } - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - userData.molbioFlag = true - hemoCubeViewModel.uploadResult(resultList) - } - - if (!userData.localFlag) { - userData.localFlag = true - hemoCubeViewModel.bulkAddResultTestToDb(userData) - } - } + Log.d("USER DATA LIST SIZE", resultList.results?.count().toString()) + resultList.results?.forEach { result -> + val userData = result.rawData + Log.d("UserData", userData.toString()) + if (userData != null) { + if (!userData.localFlag) { + hemoCubeViewModel.bulkAddResultTestToDb(userData) + userData.localFlag = true + } + } + } + // Upload results after processing all userData to avoid duplicates and ensure all modifications are done + if (resultList.results?.isNotEmpty() == true) { + hemoCubeViewModel.uploadResult(resultList) + } } } else { From 80ab69c772707b5c954733a248275af0f6fd67db Mon Sep 17 00:00:00 2001 From: Mariya Date: Thu, 29 Feb 2024 14:18:09 +0530 Subject: [PATCH 08/14] added code for uploading logs only once --- .../presentation/dashboard/HomeFragment.kt | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index cee240b..108d8b6 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -338,6 +338,14 @@ class HomeFragment : Fragment() { // "Log uploaded ${response.data.data?.filename}", // Toast.LENGTH_SHORT // ).show() + + if (!hasLogsBeenUploaded()) { + // Your code to upload logs + // Assuming the upload process is initiated here + + // After successful upload, save the flag + saveUploadSuccessFlag(true) + } } is Result.Error -> { @@ -378,7 +386,7 @@ class HomeFragment : Fragment() { response.exception.let { message -> Toast.makeText( activity, - "An error occurred in uploading logs: $message", + "$message", Toast.LENGTH_LONG ) .show() @@ -1097,4 +1105,14 @@ class HomeFragment : Fragment() { return matchResult?.groups?.get(1)?.value ?: "" } + private fun saveUploadSuccessFlag(isSuccess: Boolean) { + sharedPreference = requireActivity().getSharedPreferences("AppPrefs", Context.MODE_PRIVATE) + sharedPreference.edit().putBoolean("LogsUploaded", isSuccess).apply() + } + private fun hasLogsBeenUploaded(): Boolean { + sharedPreference = requireActivity().getSharedPreferences("AppPrefs", Context.MODE_PRIVATE) + return sharedPreference.getBoolean("LogsUploaded", false) + } + + } From 1e5afa0a5cef35271f064b9ddb4a76da597b3a2c Mon Sep 17 00:00:00 2001 From: Mariya Date: Fri, 1 Mar 2024 12:38:19 +0530 Subject: [PATCH 09/14] reduced number api calls for bigtec --- .../data/repository/DatabaseRepository.kt | 33 ++++---- .../hpostesting/data/repository/Repository.kt | 1 + .../presentation/dashboard/HomeFragment.kt | 82 +++++-------------- .../presentation/hemocube/HemoCubeFragment.kt | 2 + .../hemocube/HemoCubeViewModel.kt | 10 ++- 5 files changed, 53 insertions(+), 75 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt b/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt index 4c49cc8..4590798 100644 --- a/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt +++ b/app/src/main/java/com/example/hpostesting/data/repository/DatabaseRepository.kt @@ -109,20 +109,7 @@ class DatabaseRepository @Inject constructor( } override suspend fun addTestToDatabase(data: UserData?): Response { - return try { - val userdata = - db.collection("patientData").whereEqualTo("_id", data!!._id).get().await() - if (userdata.documents.isNotEmpty()) { - userdata.documents.forEach { - db.collection("patientData").document(it.id).update("testStatus", true) - } - } - db.collection("testData").add(data).await() - Response.Success(data._id) - } catch (e: Exception) { - Firebase.crashlytics.recordException(e) - Response.Error(e) - } + TODO("Not yet implemented") } override suspend fun addTestToDatabaseforBufferCheck(data: BufferCheckData?): Response { @@ -247,4 +234,22 @@ class DatabaseRepository @Inject constructor( override fun addTestToDatabase(testDetails: UserData): Any { TODO("Not yet implemented") } + + override suspend fun addTestToDatabasefornew(data: HemoCubeTestData?): Response { + return try { + val userdata = + db.collection("patientData").whereEqualTo("_id", data!!._id).get().await() + if (userdata.documents.isNotEmpty()) { + userdata.documents.forEach { + db.collection("patientData").document(it.id).update("testStatus", true) + } + } + db.collection("testData").add(data).await() + Response.Success(data._id) + } catch (e: Exception) { + Firebase.crashlytics.recordException(e) + Response.Error(e) + } + } + } \ No newline at end of file diff --git a/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt b/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt index 8c3f995..6322dc4 100644 --- a/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt +++ b/app/src/main/java/com/example/hpostesting/data/repository/Repository.kt @@ -25,6 +25,7 @@ import okhttp3.ResponseBody interface Repository { suspend fun addTestToDatabase(data: HemoCubeTestData?): Response + suspend fun addTestToDatabasefornew(data: HemoCubeTestData?): Response suspend fun addTestToDatabase(data: UserData?): Response diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index 108d8b6..70ae123 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -180,13 +180,13 @@ class HomeFragment : Fragment() { if (userData != null) { if (!userData.localFlag) { hemoCubeViewModel.bulkAddResultTestToDb(userData) - userData.localFlag = true + } } } // Upload results after processing all userData to avoid duplicates and ensure all modifications are done if (resultList.results?.isNotEmpty() == true) { - hemoCubeViewModel.uploadResult(resultList) + hemoCubeViewModel.uploadResultfornew(resultList) } } @@ -268,35 +268,16 @@ class HomeFragment : Fragment() { var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString() deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() if (userID.isNotEmpty() && password.isNotEmpty()) { - if (!isTokenAvailable) { + if (!isTokenAvailable || isTokenExpired(accessToken)) { hemoCubeViewModel.login(createLoginRequestData(userID, password)) } else { - if (isTokenExpired(accessToken)) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } else { isTokenAvailable = true - hemoCubeViewModel.uploadLogs() hemoCubeViewModel.startPeriodicCheckUpdate() - hemoCubeViewModel.downloadClientCertificate() hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) - } } - } else if (deviceId.isNotEmpty()) { + } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { fetchDeviceCredentials() - // This code will execute after credentials have been successfully fetched and stored. - userID = sharedPreference.getString("username", "").toString() - password = sharedPreference.getString("password", "").toString() - accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() - if (accessToken.isEmpty()) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } else { - // Continue with your existing logic if the token is not empty. - isTokenAvailable = true - hemoCubeViewModel.uploadLogs() - hemoCubeViewModel.startPeriodicCheckUpdate() - hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) - } } else { Toast.makeText( requireContext(), @@ -339,13 +320,6 @@ class HomeFragment : Fragment() { // Toast.LENGTH_SHORT // ).show() - if (!hasLogsBeenUploaded()) { - // Your code to upload logs - // Assuming the upload process is initiated here - - // After successful upload, save the flag - saveUploadSuccessFlag(true) - } } is Result.Error -> { @@ -384,12 +358,12 @@ class HomeFragment : Fragment() { is Result.Error -> { response.exception.let { message -> - Toast.makeText( - activity, - "$message", - Toast.LENGTH_LONG - ) - .show() +// Toast.makeText( +// activity, +// "$message", +// Toast.LENGTH_LONG +// ) +// .show() } } @@ -406,23 +380,21 @@ class HomeFragment : Fragment() { is Result.Success -> { val url = response.data - val fileName = "nats_certificate.zip" val downloadDirectory = "NATS" - val file = downloadFile(url, requireContext(), fileName, downloadDirectory) -// Toast.makeText( -// requireContext(), -// "NATS certificate Downloaded", -// Toast.LENGTH_SHORT -// ).show() + val fileName = "nats_certificate.zip" + val unzipDirectoryPath = requireContext().getExternalFilesDir(null)?.absolutePath + "/$downloadDirectory" + + // Check if the directory with extracted files exists. + val directory = File(unzipDirectoryPath) + if (directory.exists() && directory.isDirectory) { + // Assuming if the directory exists, the certificate has been downloaded and extracted. + // You can add more specific checks here, e.g., checking for specific files within the directory. + Toast.makeText(requireContext(), "NATS certificate already downloaded and extracted.", Toast.LENGTH_SHORT).show() + return@observe + } + val file = downloadFile(url, requireContext(), fileName, downloadDirectory) - val unzipDirectoryPath = - requireContext().getExternalFilesDir(null)?.absolutePath + "/$downloadDirectory" unzip(file.absolutePath, unzipDirectoryPath) -// Toast.makeText( -// requireContext(), -// "NATS certificate Extracted", -// Toast.LENGTH_SHORT -// ).show() } is Result.Error -> { @@ -1105,14 +1077,4 @@ class HomeFragment : Fragment() { return matchResult?.groups?.get(1)?.value ?: "" } - private fun saveUploadSuccessFlag(isSuccess: Boolean) { - sharedPreference = requireActivity().getSharedPreferences("AppPrefs", Context.MODE_PRIVATE) - sharedPreference.edit().putBoolean("LogsUploaded", isSuccess).apply() - } - private fun hasLogsBeenUploaded(): Boolean { - sharedPreference = requireActivity().getSharedPreferences("AppPrefs", Context.MODE_PRIVATE) - return sharedPreference.getBoolean("LogsUploaded", false) - } - - } diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt index 753d2c9..9e43eb8 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt @@ -161,6 +161,8 @@ class HemoCubeFragment : Fragment() { ) } handleReadingFinish() + hemoCubeViewModel.uploadLogs() + hemoCubeViewModel.downloadClientCertificate() } is Result.Error -> { diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt index 3fd4d05..ef9fefa 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt @@ -142,6 +142,14 @@ class HemoCubeViewModel @Inject constructor( } } + + fun uploadResultfornew(molbioV2ResultRequest: MolbioV2ResultRequest) = viewModelScope.launch { + resultUpload.postValue(Result.Loading()) + repository.uploadResults(molbioV2ResultRequest).let { + resultUpload.postValue(it) + } + } + fun checkUpdate(checkUpdateRequest: CheckUpdateRequest) = viewModelScope.launch { checkUpdate.postValue(Result.Loading()) repository.checkUpdate(checkUpdateRequest).let { @@ -363,7 +371,7 @@ class HemoCubeViewModel @Inject constructor( userData.reportUploadTime = SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() ).format(Calendar.getInstance().time) - when (repository.addTestToDatabase(userData)) { + when (repository.addTestToDatabasefornew(userData)) { is Response.Success -> { fireBaseBulkUpload.postValue("Success") updateLocalFlag(userData._id) From b68ec45642dd94407d5c43efee264025895a1d9e Mon Sep 17 00:00:00 2001 From: Mariya Date: Fri, 1 Mar 2024 13:37:16 +0530 Subject: [PATCH 10/14] reduced number of api calls in home screen --- .../dashboard/DashboardActivity.kt | 2 - .../presentation/dashboard/HomeFragment.kt | 37 ++++++++++++------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt index 009662c..cafeb61 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/DashboardActivity.kt @@ -100,8 +100,6 @@ class DashboardActivity : AppCompatActivity(), IDataCollector { val apk = result.data val file = File(getExternalFilesDir("Updates"), "update.apk") file.setReadable(true, false) // Ensure the file is readable - - apk.byteStream().use { input -> file.outputStream().use { output -> input.copyTo(output) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index 70ae123..cc32501 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -267,14 +267,12 @@ class HomeFragment : Fragment() { var password = sharedPreference.getString(Constants.DEVICE_PASSWORD_API, "").toString() var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString() deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() - if (userID.isNotEmpty() && password.isNotEmpty()) { - if (!isTokenAvailable || isTokenExpired(accessToken)) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } else { - isTokenAvailable = true - hemoCubeViewModel.startPeriodicCheckUpdate() - hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) + if (!isTokenAvailable) { + if(userID.isNotEmpty() || password.isNotEmpty()) { + if(isTokenExpired(accessToken)) { + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + } } } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { fetchDeviceCredentials() @@ -290,6 +288,9 @@ class HomeFragment : Fragment() { when (response) { is Result.Success -> { updateTokens(response) + isTokenAvailable = true + hemoCubeViewModel.startPeriodicCheckUpdate() + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) } is Result.Error -> { @@ -326,7 +327,7 @@ class HomeFragment : Fragment() { response.exception.let { message -> Toast.makeText( activity, - "An error occurred in uploading logs: $message", + "$message", Toast.LENGTH_LONG ) .show() @@ -344,13 +345,23 @@ class HomeFragment : Fragment() { hemoCubeViewModel.checkUpdate.observe(viewLifecycleOwner) { response -> when (response) { is Result.Success -> { - // Handle success - val apkUrl = response.data - Log.e("ApI", "APK URL: $apkUrl") - hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) + val updatedversion = response.data.data?.version.toString() + val currentversion = + context?.let { context?.packageManager!!.getPackageInfo(it.packageName, 0) } + if(updatedversion > currentversion.toString()){ + hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) + }else{ + Toast.makeText( + activity, + "App is Up to date", + Toast.LENGTH_LONG + ) + .show() + } + Toast.makeText( activity, - " ${response.data}", + "new version ${response.data.data?.version} Available", Toast.LENGTH_LONG ) .show() From 210c9fed5d29be7478f7ad36e4c2ee156b7a7331 Mon Sep 17 00:00:00 2001 From: Mariya Date: Fri, 1 Mar 2024 16:21:27 +0530 Subject: [PATCH 11/14] added code for usb permission --- .../presentation/dashboard/HomeFragment.kt | 20 +++++----- .../presentation/hemocube/HemocubeActivity.kt | 37 +++++++++++++------ 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index cc32501..fb1906a 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -267,13 +267,16 @@ class HomeFragment : Fragment() { var password = sharedPreference.getString(Constants.DEVICE_PASSWORD_API, "").toString() var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString() deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() - - if (!isTokenAvailable) { - if(userID.isNotEmpty() || password.isNotEmpty()) { - if(isTokenExpired(accessToken)) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } - } + if(userID.isNotEmpty() && password.isNotEmpty()) { + if (!isTokenAvailable) { + if(isTokenExpired(accessToken)) { + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + } + }else{ + isTokenAvailable = true + hemoCubeViewModel.startPeriodicCheckUpdate() + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) + } } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { fetchDeviceCredentials() } else { @@ -288,9 +291,8 @@ class HomeFragment : Fragment() { when (response) { is Result.Success -> { updateTokens(response) + response.data.data?.accessToken isTokenAvailable = true - hemoCubeViewModel.startPeriodicCheckUpdate() - hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) } is Result.Error -> { diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt index ca5edf2..aff99fc 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt @@ -11,12 +11,14 @@ import android.content.ServiceConnection import android.hardware.usb.UsbDevice import android.hardware.usb.UsbDeviceConnection import android.hardware.usb.UsbManager +import android.os.Build import android.os.Bundle import android.os.IBinder import android.util.Log import android.view.Menu import android.widget.Toast import androidx.activity.viewModels +import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.get @@ -43,6 +45,7 @@ open class HemocubeActivity : AppCompatActivity() { private val TAG = "HemoCube" private val broadcastReceiver = object : BroadcastReceiver() { + @RequiresApi(Build.VERSION_CODES.O) override fun onReceive(context: Context, intent: Intent) { synchronized(this) { @@ -82,6 +85,7 @@ open class HemocubeActivity : AppCompatActivity() { super.attachBaseContext(newBase) } + @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHemocubeBinding.inflate(layoutInflater) @@ -106,6 +110,7 @@ open class HemocubeActivity : AppCompatActivity() { } } + @RequiresApi(Build.VERSION_CODES.O) open fun connectUsb(permissionGranted: Boolean) { Log.d(TAG, "connectUsb() called, permission variable = $permissionGranted") val manager = getSystemService(Context.USB_SERVICE) as UsbManager @@ -125,32 +130,40 @@ open class HemocubeActivity : AppCompatActivity() { } } - @SuppressLint("MutableImplicitPendingIntent") + @RequiresApi(Build.VERSION_CODES.O) + @SuppressLint("UnspecifiedImmutableFlag") private fun requestUserPermission(manager: UsbManager, device: UsbDevice) { val mPendingIntent: PendingIntent - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { - mPendingIntent = PendingIntent.getBroadcast( - this, 0, Intent(Constants.HEMOCUBE_USB_PERMISSION), PendingIntent.FLAG_MUTABLE - ) - } else { - mPendingIntent = PendingIntent.getBroadcast( - this, - 0, - Intent(Constants.HEMOCUBE_USB_PERMISSION), + val pendingIntentFlags = when { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + PendingIntent.FLAG_IMMUTABLE + } + else -> { 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) - registerReceiver(broadcastReceiver, filter) + registerReceiver(broadcastReceiver, filter, RECEIVER_EXPORTED) + + // Request permission manager.requestPermission(device, mPendingIntent) } + fun setupService() { val intent = Intent(this, UsbService::class.java) bindService(intent, connection, Context.BIND_AUTO_CREATE) } + @RequiresApi(Build.VERSION_CODES.O) open fun reconnectDevice() { mService.disconnect() unbindService(connection) From c8d5d41c816141d1159eb8a6b309e6c6e5c5a778 Mon Sep 17 00:00:00 2001 From: Mariya Date: Sat, 2 Mar 2024 15:41:17 +0530 Subject: [PATCH 12/14] api calls maintaining for molbio --- .../presentation/dashboard/HomeFragment.kt | 87 ++++++++++++++----- .../presentation/hemocube/HemocubeActivity.kt | 27 +++--- 2 files changed, 74 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index fb1906a..df77e47 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -7,6 +7,7 @@ import android.content.DialogInterface import android.content.Intent import android.content.SharedPreferences import android.os.BatteryManager +import android.os.Build import android.os.Bundle import android.util.Base64 import android.util.Log @@ -14,6 +15,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast +import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController @@ -88,6 +90,7 @@ class HomeFragment : Fragment() { return binding.root } + @RequiresApi(Build.VERSION_CODES.P) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) @@ -135,6 +138,7 @@ class HomeFragment : Fragment() { checkForTokenAndUpdate() } + // Now re-subscribe to allUserData hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { originalUserDataList -> 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 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() { var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() var password = sharedPreference.getString(Constants.DEVICE_PASSWORD_API, "").toString() var userID = sharedPreference.getString(Constants.DEVICE_ID_API, "").toString() deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() if(userID.isNotEmpty() && password.isNotEmpty()) { + Log.d("istoken",isTokenAvailable.toString()) if (!isTokenAvailable) { + Log.d("istoken1",isTokenAvailable.toString()) if(isTokenExpired(accessToken)) { hemoCubeViewModel.login(createLoginRequestData(userID, password)) } @@ -279,6 +286,14 @@ class HomeFragment : Fragment() { } } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { 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 { Toast.makeText( requireContext(), @@ -293,6 +308,7 @@ class HomeFragment : Fragment() { updateTokens(response) response.data.data?.accessToken isTokenAvailable = true + Log.d("istoken2",isTokenAvailable.toString()) } is Result.Error -> { @@ -349,9 +365,30 @@ class HomeFragment : Fragment() { is Result.Success -> { val updatedversion = response.data.data?.version.toString() 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()){ hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData()) + Toast.makeText( + activity, + "new version ${response.data.data?.version} Available", + Toast.LENGTH_LONG + ) + .show() }else{ Toast.makeText( activity, @@ -360,24 +397,17 @@ class HomeFragment : Fragment() { ) .show() } - - Toast.makeText( - activity, - "new version ${response.data.data?.version} Available", - Toast.LENGTH_LONG - ) - .show() } is Result.Error -> { - response.exception.let { message -> -// Toast.makeText( -// activity, -// "$message", -// Toast.LENGTH_LONG -// ) -// .show() - } +// response.exception.let { message -> +//// Toast.makeText( +//// activity, +//// "$message", +//// Toast.LENGTH_LONG +//// ) +//// .show() +// } } is Result.Loading -> { @@ -459,14 +489,18 @@ class HomeFragment : Fragment() { private fun isTokenExpired(token: String): Boolean { - val parts = token.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - val decodedPayload = String(Base64.decode(parts[1], Base64.DEFAULT)) - val jsonPayload = JSONObject(decodedPayload) + if(token.isNotEmpty()) { + val parts = token.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val decodedPayload = String(Base64.decode(parts[1], Base64.DEFAULT)) + val jsonPayload = JSONObject(decodedPayload) - val exp = jsonPayload.optLong("exp", 0) - val currentTimeSeconds = System.currentTimeMillis() / 1000 + val exp = jsonPayload.optLong("exp", 0) + val currentTimeSeconds = System.currentTimeMillis() / 1000 - return exp <= currentTimeSeconds + return exp <= currentTimeSeconds + }else{ + return false + } } private fun updateTokens(response: Result.Success) { @@ -479,6 +513,7 @@ class HomeFragment : Fragment() { apply() } isTokenAvailable = true + Log.d("istoken3",isTokenAvailable.toString()) } private fun createLoginRequestData(userID: String, password: String): LoginRequest { @@ -620,7 +655,11 @@ class HomeFragment : Fragment() { putString(Constants.NATS_TOKEN, natsToken) 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.") } else { Log.e("fetchDeviceCredentials", "Document does not exist.") diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt index aff99fc..64f14ea 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemocubeActivity.kt @@ -131,29 +131,24 @@ open class HemocubeActivity : AppCompatActivity() { } @RequiresApi(Build.VERSION_CODES.O) - @SuppressLint("UnspecifiedImmutableFlag") + @SuppressLint("MutableImplicitPendingIntent") private fun requestUserPermission(manager: UsbManager, device: UsbDevice) { val mPendingIntent: PendingIntent - val pendingIntentFlags = when { - Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { - PendingIntent.FLAG_IMMUTABLE - } - else -> { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { + mPendingIntent = PendingIntent.getBroadcast( + this, 0, Intent(Constants.HEMOCUBE_USB_PERMISSION), PendingIntent.FLAG_MUTABLE + ) + } else { + mPendingIntent = PendingIntent.getBroadcast( + this, + 0, + Intent(Constants.HEMOCUBE_USB_PERMISSION), 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) registerReceiver(broadcastReceiver, filter, RECEIVER_EXPORTED) - - // Request permission manager.requestPermission(device, mPendingIntent) } From 20f408230e36a1effd087684d0d1ee408b91a10c Mon Sep 17 00:00:00 2001 From: Mariya Date: Sat, 2 Mar 2024 19:37:24 +0530 Subject: [PATCH 13/14] api calls managing, and error resolving for molbio --- app/build.gradle | 4 +- .../presentation/dashboard/HomeFragment.kt | 130 +++++++----------- .../presentation/hemocube/HemoCubeFragment.kt | 3 +- .../hemocube/HemoCubeViewModel.kt | 3 +- 4 files changed, 57 insertions(+), 83 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 1fc3875..15f5b63 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -19,8 +19,8 @@ android { applicationId "in.sminnovations.hpostesting.dev" minSdk 21 targetSdk 34 - versionCode 117 - versionName "2.1.117" + versionCode 119 + versionName "2.1.119" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index df77e47..6bf57a1 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -188,9 +188,14 @@ class HomeFragment : Fragment() { } } } + + var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() // Upload results after processing all userData to avoid duplicates and ensure all modifications are done - if (resultList.results?.isNotEmpty() == true) { - hemoCubeViewModel.uploadResult(resultList) + if(accessToken.isNotEmpty()) { + if (resultList.results?.isNotEmpty() == true) { + hemoCubeViewModel.uploadResult(resultList) + Log.d("resultcount1","resultcount") + } } } @@ -217,7 +222,7 @@ class HomeFragment : Fragment() { } binding.uploadData.setOnClickListener { - showUploadDialog(requireContext()) +// showUploadDialog(requireContext()) } hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userData -> @@ -274,26 +279,23 @@ class HomeFragment : Fragment() { deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() if(userID.isNotEmpty() && password.isNotEmpty()) { Log.d("istoken",isTokenAvailable.toString()) - if (!isTokenAvailable) { - Log.d("istoken1",isTokenAvailable.toString()) - if(isTokenExpired(accessToken)) { - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - } - }else{ + if (isTokenAvailable) { + Log.d("istoken7",isTokenAvailable.toString()) isTokenAvailable = true hemoCubeViewModel.startPeriodicCheckUpdate() hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) + }else{ + if(isTokenExpired(accessToken)) { + Log.d("istoken8",isTokenAvailable.toString()) + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + }else { + Log.d("istoken1",isTokenAvailable.toString()) + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + isTokenAvailable = true + } } } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { 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 { Toast.makeText( requireContext(), @@ -624,6 +626,7 @@ class HomeFragment : Fragment() { } } + @RequiresApi(Build.VERSION_CODES.P) private fun fetchDeviceCredentials() { try { val db = Firebase.firestore @@ -650,13 +653,13 @@ class HomeFragment : Fragment() { ) // Save credentials in SharedPreferences with(sharedPreference.edit()) { - putString("username", username) - putString("password", password) + putString(Constants.DEVICE_ID_API, username) + putString(Constants.DEVICE_PASSWORD_API, password) putString(Constants.NATS_TOKEN, natsToken) apply() } if (!isTokenAvailable ) { - Log.d("istoken1", isTokenAvailable.toString()) + Log.d("istoken0", isTokenAvailable.toString()) hemoCubeViewModel.login(createLoginRequestData(username, password)) } @@ -854,7 +857,7 @@ class HomeFragment : Fragment() { builder.setMessage(R.string.upload_db_registration_message) builder.setPositiveButton(R.string.upload) { dialog, _ -> - uploadLocalDBData(dialog) +// uploadLocalDBData(dialog) } builder.setNegativeButton(R.string.cancel) { dialog, _ -> @@ -900,34 +903,34 @@ class HomeFragment : Fragment() { hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> val resultList = MolbioV2ResultRequest(mutableListOf(MolbioV2Result())) - userDataList.forEach { userData -> - if (!userData.molbioFlag && isTokenAvailable) { - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = "2024-02-08 16:33:56", //userData.reportUploadTime, - analysisStatus = userData.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), - interpretation = userData.classificationResult, - testId = userData._id, - testTime = userData.testTime, - collectionTime = "2024-02-08 16:33:56",//userData.testTime, - expiryTime = "2024-02-08 16:33:56",//userData.testTime, - ) - ) +// userDataList.forEach { userData -> +// if (!userData.molbioFlag && isTokenAvailable) { +// resultList.results?.add( +// MolbioV2Result( +// rawData = userData, +// analysisId = userData._id, +// analysisDate = "2024-02-08 16:33:56", //userData.reportUploadTime, +// analysisStatus = userData.classificationResult, +// thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), +// interpretation = userData.classificationResult, +// testId = userData._id, +// testTime = userData.testTime, +// collectionTime = "2024-02-08 16:33:56",//userData.testTime, +// expiryTime = "2024-02-08 16:33:56",//userData.testTime, +// ) +// ) +// +// } - } - - if (!userData.localFlag) { - userData.localFlag = true - hemoCubeViewModel.bulkAddResultTestToDb(userData) - } - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - userData.molbioFlag = true - hemoCubeViewModel.uploadResult(resultList) - } - } +// if (!userData.localFlag) { +// userData.localFlag = true +// hemoCubeViewModel.bulkAddResultTestToDb(userData) +// } +// if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { +// userData.molbioFlag = true +// hemoCubeViewModel.uploadResult(resultList) +// } +// } dialog.dismiss() } @@ -940,37 +943,6 @@ class HomeFragment : Fragment() { } dialog.dismiss() } - - hemoCubeViewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> - val resultList = MolbioV2ResultRequest(mutableListOf(MolbioV2Result())) - userDataList.forEach { userData -> - if (!userData.molbioFlag && isTokenAvailable) { - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = "2024-02-08 16:33:56",//userData.testTime, - analysisStatus = userData.classificationResult, - thresholds = Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId].toString(), - interpretation = userData.classificationResult, - testId = userData._id, - testTime = "2024-02-08 16:33:56",//userData.testTime, - collectionTime = "2024-02-08 16:33:56",//userData.testTime, - expiryTime = "2024-02-08 16:33:56"//userData.testTime, - ) - ) - userData.molbioFlag = true - hemoCubeViewModel.uploadResult(resultList) - } - - if (!userData.localFlag) { - userData.localFlag = true - hemoCubeViewModel.bulkAddResultTestToDb(userData) - } - - } - dialog.dismiss() - } } // private fun downloadLocalDBData(dialog: DialogInterface) { diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt index 9e43eb8..c710a49 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt @@ -149,8 +149,9 @@ class HemoCubeFragment : Fragment() { hemoCubeViewModel.fireBaseUpload.observe(viewLifecycleOwner) { result -> if (result == "Success") { uploadedToCloud = true + var accessToken = sharedPreferences.getString(Constants.ACCESS_TOKEN, "").toString() showToast(R.string.test_upload) - if (Constants.MOLBIO_INTEGRATION) { + if (Constants.MOLBIO_INTEGRATION && accessToken.isNotEmpty()) { hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { when (it) { is Result.Success -> { diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt index ef9fefa..25671ca 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt @@ -328,7 +328,8 @@ class HemoCubeViewModel @Inject constructor( Log.i("Testdb", "Data uploaded to Firestore successfully") fireBaseUpload.postValue("Success") testDetails.localFlag = true - if (Constants.MOLBIO_INTEGRATION) { + var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() + if (Constants.MOLBIO_INTEGRATION && accessToken.isNotEmpty()) { uploadResult( MolbioV2ResultRequest( mutableListOf( From c9d0c440e39b1526d0bb8deaf2adcb0d01ce7692 Mon Sep 17 00:00:00 2001 From: Mariya Date: Mon, 4 Mar 2024 14:48:43 +0530 Subject: [PATCH 14/14] added code for sanitize result upload values if if the result is NAN or infinity for molbio integration --- app/build.gradle | 4 +- .../presentation/dashboard/HomeFragment.kt | 151 ++++++++++-------- .../presentation/hemocube/HemoCubeFragment.kt | 2 +- .../hemocube/HemoCubeViewModel.kt | 5 +- 4 files changed, 94 insertions(+), 68 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 15f5b63..2765cb5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -19,8 +19,8 @@ android { applicationId "in.sminnovations.hpostesting.dev" minSdk 21 targetSdk 34 - versionCode 119 - versionName "2.1.119" + versionCode 120 + versionName "2.1.120" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index 6bf57a1..639b5c0 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -149,31 +149,34 @@ class HomeFragment : Fragment() { ": USER DATA", originalUserDataList.count().toString() + " : " + userData._id ) - - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - val currentTimeFormatted = SimpleDateFormat( - "yyyy-MM-dd'T'HH:mm:ssZZZZZ", - Locale.getDefault() - ).format(Calendar.getInstance().time) - val bufferIntensityThreshold = - Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId]?.toString() - ?: "defaultThreshold" // Handle possible nulls safely - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = currentTimeFormatted, - analysisStatus = userData.classificationResult - ?: "defaultStatus", // Handle possible nulls - thresholds = bufferIntensityThreshold, - interpretation = userData.classificationResult - ?: "defaultInterpretation", // Handle possible nulls - testId = userData._id, - testTime = currentTimeFormatted, - collectionTime = currentTimeFormatted, - expiryTime = currentTimeFormatted + var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() + // Upload results after processing all userData to avoid duplicates and ensure all modifications are done + if(accessToken.isNotEmpty()) { + if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { + val currentTimeFormatted = SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + Locale.getDefault() + ).format(Calendar.getInstance().time) + val bufferIntensityThreshold = + Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId]?.toString() + ?: "defaultThreshold" // Handle possible nulls safely + resultList.results?.add( + MolbioV2Result( + rawData = userData, + analysisId = userData._id, + analysisDate = currentTimeFormatted, + analysisStatus = userData.classificationResult + ?: "defaultStatus", // Handle possible nulls + thresholds = bufferIntensityThreshold, + interpretation = userData.classificationResult + ?: "defaultInterpretation", // Handle possible nulls + testId = userData._id, + testTime = currentTimeFormatted, + collectionTime = currentTimeFormatted, + expiryTime = currentTimeFormatted + ) ) - ) + } } } Log.d("USER DATA LIST SIZE", resultList.results?.count().toString()) @@ -188,15 +191,16 @@ class HomeFragment : Fragment() { } } } - - var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() - // Upload results after processing all userData to avoid duplicates and ensure all modifications are done - if(accessToken.isNotEmpty()) { - if (resultList.results?.isNotEmpty() == true) { - hemoCubeViewModel.uploadResult(resultList) - Log.d("resultcount1","resultcount") - } + resultList.results?.forEach { result -> + result.rawData?.let { sanitizeDoubleValues(it) } } + +// Then, check if there are any results to upload. + if (resultList.results?.isNotEmpty() == true) { + hemoCubeViewModel.uploadResult(resultList) + Log.d("resultcount1", "Uploading sanitized results") + } + } } else { @@ -279,19 +283,20 @@ class HomeFragment : Fragment() { deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString() if(userID.isNotEmpty() && password.isNotEmpty()) { Log.d("istoken",isTokenAvailable.toString()) - if (isTokenAvailable) { + if (!isTokenAvailable) { + Log.d("istoken1",isTokenAvailable.toString()) + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + isTokenAvailable = true + + }else if(isTokenAvailable){ Log.d("istoken7",isTokenAvailable.toString()) isTokenAvailable = true hemoCubeViewModel.startPeriodicCheckUpdate() hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) - }else{ + }else{ if(isTokenExpired(accessToken)) { Log.d("istoken8",isTokenAvailable.toString()) hemoCubeViewModel.login(createLoginRequestData(userID, password)) - }else { - Log.d("istoken1",isTokenAvailable.toString()) - hemoCubeViewModel.login(createLoginRequestData(userID, password)) - isTokenAvailable = true } } } else if (userID.isEmpty() && password.isEmpty() && deviceId.isNotEmpty()) { @@ -332,6 +337,36 @@ class HomeFragment : Fragment() { } } + hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { + when (it) { + is Result.Success -> { + + Log.d("success,","uploded") + it.data.data?.forEach { id -> + id.rawData?.let { it1 -> + hemoCubeViewModel.updateMolbioFlag( + it1._id + ) + } + } + Toast.makeText(activity, "Molbio Result is successfully uploaded", Toast.LENGTH_LONG) + .show() + } + + is Result.Error -> { + binding.btnSubmit.visibility = View.VISIBLE + //Remove this line of code while deploying to IOCL + it.exception.let { message -> + Toast.makeText(activity, "$message", Toast.LENGTH_LONG) + .show() + Log.d("resultuploadfail", message.toString()) + } + } + + else -> {} + } + } + hemoCubeViewModel.uploadLogs.observe(viewLifecycleOwner) { response -> when (response) { is Result.Success -> { @@ -461,31 +496,6 @@ class HomeFragment : Fragment() { } } - hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { - when (it) { - is Result.Success -> { - it.data.data?.forEach { id -> - id.rawData?.let { it1 -> - hemoCubeViewModel.updateMolbioFlag( - it1._id - ) - } - } - } - - is Result.Error -> { - binding.btnSubmit.visibility = View.VISIBLE - //Remove this line of code while deploying to IOCL - it.exception.let { message -> - Toast.makeText(activity, "An error occurred: $message", Toast.LENGTH_LONG) - .show() - } - } - - else -> {} - } - } - } @@ -851,6 +861,21 @@ class HomeFragment : Fragment() { } } + private fun sanitizeDoubleValues(hemoCubeTestData: HemoCubeTestData): HemoCubeTestData { + hemoCubeTestData::class.java.declaredFields.forEach { field -> + if (field.type == Double::class.javaObjectType || field.type == Double::class.javaPrimitiveType) { + field.isAccessible = true + val value = field.get(hemoCubeTestData) as Double? + if (value != null && (value.isInfinite() || value.isNaN())) { + field.set(hemoCubeTestData, 0.0) // Replace with a suitable default value + } + } + } + return hemoCubeTestData + } + + + private fun showUploadDialog(context: Context) { val builder = AlertDialog.Builder(context) builder.setTitle(R.string.upload_db_registration_title) diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt index c710a49..f6ef870 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt @@ -151,7 +151,7 @@ class HemoCubeFragment : Fragment() { uploadedToCloud = true var accessToken = sharedPreferences.getString(Constants.ACCESS_TOKEN, "").toString() showToast(R.string.test_upload) - if (Constants.MOLBIO_INTEGRATION && accessToken.isNotEmpty()) { + if (Constants.MOLBIO_INTEGRATION) { hemoCubeViewModel.resultUpload.observe(viewLifecycleOwner) { when (it) { is Result.Success -> { diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt index 25671ca..dcfd891 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeViewModel.kt @@ -328,8 +328,7 @@ class HemoCubeViewModel @Inject constructor( Log.i("Testdb", "Data uploaded to Firestore successfully") fireBaseUpload.postValue("Success") testDetails.localFlag = true - var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() - if (Constants.MOLBIO_INTEGRATION && accessToken.isNotEmpty()) { + if (Constants.MOLBIO_INTEGRATION) { uploadResult( MolbioV2ResultRequest( mutableListOf( @@ -417,6 +416,8 @@ class HemoCubeViewModel @Inject constructor( Log.e("Testdb", "Error uploading data to Firestore: $response") fireBaseUpload.postValue("Error") } + + else -> {} } } catch (e: Exception) { Log.e("Testdb", "Exception during data upload: ${e.message}")