From c492d8ee418b256bd7faf508547efd19aab058e3 Mon Sep 17 00:00:00 2001 From: JC Date: Wed, 14 Feb 2024 11:35:15 -0700 Subject: [PATCH 01/41] fix: BackgroungSync service removed & simplest Task scheduling done --- android/app/src/main/AndroidManifest.xml | 1 - .../org/ZingoLabs/Zingo/BackgroundSync.kt | 21 --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 21 +++ .../java/org/ZingoLabs/Zingo/MainActivity.kt | 59 +++++--- app/BackgroundSync.ts | 129 ------------------ app/LoadedApp/LoadedApp.tsx | 5 +- app/LoadingApp/LoadingApp.tsx | 11 +- index.js | 2 - 8 files changed, 68 insertions(+), 181 deletions(-) delete mode 100644 android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSync.kt create mode 100644 android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt delete mode 100644 app/BackgroundSync.ts diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index a0b43f231..de88364e4 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -38,7 +38,6 @@ - diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSync.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSync.kt deleted file mode 100644 index 940058f97..000000000 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSync.kt +++ /dev/null @@ -1,21 +0,0 @@ -package org.ZingoLabs.Zingo - -import android.content.Intent -import com.facebook.react.HeadlessJsTaskService -import com.facebook.react.bridge.Arguments -import com.facebook.react.jstasks.HeadlessJsTaskConfig - - class BackgroundSync : HeadlessJsTaskService() { - override fun getTaskConfig(intent: Intent): HeadlessJsTaskConfig? { - return intent.extras?.let { - HeadlessJsTaskConfig( - "BackgroundSync", - Arguments.fromBundle(it), - 0, // timeout for the task - true // optional: defines whether or not the task is allowed in foreground. - // Default is false - ) - } - } -} - diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt new file mode 100644 index 000000000..5192c830a --- /dev/null +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -0,0 +1,21 @@ +package org.ZingoLabs.Zingo + +import android.content.Context +import androidx.work.Worker +import androidx.work.WorkerParameters +import android.util.Log + +class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { + + override fun doWork(): Result { + val logMessage = inputData.getString("log_message") + Log.w("SCHEDULED_TASK_RUN", logMessage ?: "No message provided") + + // checking if the wallet file exists + + + + + return Result.success() + } +} \ No newline at end of file diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 9633ecded..f6397ffda 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -3,8 +3,10 @@ package org.ZingoLabs.Zingo import android.content.Intent import android.os.Bundle import android.util.Log +import androidx.work.* import com.facebook.react.ReactActivity import java.util.concurrent.TimeUnit +import java.util.Calendar class MainActivity : ReactActivity() { /** @@ -15,30 +17,55 @@ class MainActivity : ReactActivity() { return "Zingo!" } override fun onCreate(savedInstanceState: Bundle?) { - Log.w("", "Starting main activity") - val service = Intent(applicationContext, BackgroundSync::class.java) - applicationContext.stopService(service) + Log.w("ON_CREATE", "Starting main activity") super.onCreate(null) } override fun onPause() { - Log.w("", "Pausing main activity") - val service = Intent(applicationContext, BackgroundSync::class.java) - val bundle = Bundle() - - bundle.putString("BS: start syncing", "Native") - - service.putExtras(bundle) - - applicationContext.startService(service) + Log.w("ON_PAUSE", "Pausing main activity - Background") + scheduleBackgroundTask() super.onPause() - //val backgroundRequest = PeriodicWorkRequest.Builder(BackgroundWorker::class.java, 15, TimeUnit.MINUTES).build() - //WorkManager.getInstance(application).enqueue(backgroundRequest) } override fun onResume() { - val service = Intent(applicationContext, BackgroundSync::class.java) - applicationContext.stopService(service) + Log.w("ON_RESUME", "Resuming main activity - Foreground") super.onResume() } + + private fun scheduleBackgroundTask() { + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.UNMETERED) + .setRequiresCharging(true) + .setRequiresDeviceIdle(false) + .build() + + // PRODUCTION - next day at 3:00 am + val currentTime = Calendar.getInstance() + val targetTime = Calendar.getInstance().apply { + set(Calendar.HOUR_OF_DAY, 3) + set(Calendar.MINUTE, 0) + set(Calendar.SECOND, 0) + if (before(currentTime)) { + add(Calendar.DATE, 1) + } + } + val timeDifference = targetTime.timeInMillis - currentTime.timeInMillis + + // DEVELOPMENT - after 5 minutes. + val timeFiveMinutes: Long = 5 + + val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, 24, TimeUnit.HOURS) + .setConstraints(constraints) + //.setInitialDelay(timeDifference, TimeUnit.MILLISECONDS) + .setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) + .build() + + Log.w("SCHEDULING_TASK", "Enqueuing the background task - Background") + WorkManager.getInstance(this) + .enqueueUniquePeriodicWork( + "daily_background_sync", + ExistingPeriodicWorkPolicy.REPLACE, + workRequest + ) + } } \ No newline at end of file diff --git a/app/BackgroundSync.ts b/app/BackgroundSync.ts deleted file mode 100644 index e051f7be9..000000000 --- a/app/BackgroundSync.ts +++ /dev/null @@ -1,129 +0,0 @@ -import RPCModule from './RPCModule'; -import AsyncStorage from '@react-native-async-storage/async-storage'; -import NetInfo, { NetInfoStateType } from '@react-native-community/netinfo'; -import { RPCSyncStatusType } from './rpc/types/RPCSyncStatusType'; - -const BackgroundSync = async (task_data: any) => { - // this not interact with the server. - const exists = await RPCModule.walletExists(); - - // only if exists the wallet file make sense to do the sync. - if (exists && exists !== 'false') { - // only if we have connection make sense to call RPCModule. - const networkState = await NetInfo.fetch(); - if ( - !networkState.isConnected || - networkState.type === NetInfoStateType.cellular || - (networkState.details !== null && networkState.details.isConnectionExpensive) - ) { - //console.log( - // 'BS: Not started (connected: ' + networkState.isConnected, - // +', type: ' + - // networkState.type + - // +', expensive connection: ' + - // networkState.details?.isConnectionExpensive + - // ')', - //); - return; - } - // if the App goes to Foreground kill the interval - const background = await AsyncStorage.getItem('@background'); - if (background === 'no') { - //console.log('BS: Not started (going to foreground)'); - return; - } - - let batch_num = -1; - console.log('BS:', task_data); - - // finishEarly has two fields: wait, and done. - // wait() returns a promise, which is resolved when - // done() is called - let finishEarly = manuallyResolve(); - - let saver = setInterval(async () => { - const networkStateSaver = await NetInfo.fetch(); - if ( - !networkStateSaver.isConnected || - networkStateSaver.type === NetInfoStateType.cellular || - (networkStateSaver.details !== null && networkStateSaver.details.isConnectionExpensive) - ) { - //console.log( - // 'BS: Interrupted (connected: ' + networkStateSaver.isConnected, - // +', type: ' + - // networkStateSaver.type + - // +', expensive connection: ' + - // networkStateSaver.details?.isConnectionExpensive + - // ')', - //); - clearInterval(saver); - finishEarly.done(); - return; - } - // if the App goes to Foreground kill the interval - const backgroundSaver = await AsyncStorage.getItem('@background'); - if (backgroundSaver === 'no') { - clearInterval(saver); - //console.log('BS: Finished (going to foreground)'); - finishEarly.done(); - return; - } - - const syncStatusStr: string = await RPCModule.execute('syncstatus', ''); - if (syncStatusStr) { - if (syncStatusStr.toLowerCase().startsWith('error')) { - //console.log(`BS: Error sync status ${syncStatusStr}`); - return; - } - } else { - //console.log('BS: Internal Error sync status'); - return; - } - - let ss = {} as RPCSyncStatusType; - try { - ss = await JSON.parse(syncStatusStr); - } catch (e) { - //console.log('BS: Error parsing syncstatus JSON', e); - return; - } - - //console.log('BS:', ss); - if (ss.batch_num && ss.batch_num > -1 && batch_num !== ss.batch_num) { - await RPCModule.doSave(); - //console.log('BS: saving...'); - // update batch_num with the new value, otherwise never change - batch_num = ss.batch_num; - } - }, 5000); - - await Promise.race([RPCModule.execute('sync', ''), finishEarly.wait()]); - clearInterval(saver); - } else { - console.log('BS: wallet file does not exist'); - } - //console.log('BS: Finished (end of syncing)'); -}; - -export default BackgroundSync; - -function manuallyResolve() { - let resolve: Function; - // new Promise takes a function as an argument. When that function is called - // the promise resolves with the value output by that function. - // By passing the function out of the promise, we can call it later - // in order to resolve the promise at will - const promise = new Promise(fun => { - resolve = fun; - }); - - function done() { - resolve(); - } - - function wait() { - return promise; - } - - return { wait, done }; -} diff --git a/app/LoadedApp/LoadedApp.tsx b/app/LoadedApp/LoadedApp.tsx index 42a7bd70f..b51ac94e0 100644 --- a/app/LoadedApp/LoadedApp.tsx +++ b/app/LoadedApp/LoadedApp.tsx @@ -301,10 +301,7 @@ export class LoadedAppClass extends Component { - const backgroundJson = await BackgroundFileImpl.readBackground(); + const backgroundJson: BackgroundType = await BackgroundFileImpl.readBackground(); if (backgroundJson) { - this.setState({ - background: backgroundJson, - }); + this.setState({ background: backgroundJson }); } }; diff --git a/index.js b/index.js index 32168fcb8..9b7393291 100644 --- a/index.js +++ b/index.js @@ -5,7 +5,5 @@ import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; -import BackgroundSync from './app/BackgroundSync'; -AppRegistry.registerHeadlessTask('BackgroundSync', () => BackgroundSync); AppRegistry.registerComponent(appName, () => App); From 22cfc1f6f1ff2485c5240a527361d354bfcb5c7b Mon Sep 17 00:00:00 2001 From: JC Date: Wed, 14 Feb 2024 14:21:42 -0700 Subject: [PATCH 02/41] fix: native background sync process - first approach --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 77 ++++++++++++++++++- .../java/org/ZingoLabs/Zingo/RPCModule.kt | 30 +++++++- 2 files changed, 101 insertions(+), 6 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 5192c830a..985a03caa 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -4,18 +4,91 @@ import android.content.Context import androidx.work.Worker import androidx.work.WorkerParameters import android.util.Log +import java.io.File +import java.util.* +import org.json.JSONObject +import java.nio.charset.StandardCharsets class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { override fun doWork(): Result { - val logMessage = inputData.getString("log_message") - Log.w("SCHEDULED_TASK_RUN", logMessage ?: "No message provided") + Log.w("SCHEDULED_TASK_RUN", "Task running") // checking if the wallet file exists + val exits: Boolean = walletExists() + if (exits) { + // stop syncing first, just in case. + stopSyncingProcess() + // interrupt + val resp = RustFFI.execute("interrupt_sync_after_batch", "false") + Log.w("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") + // the task is running here blocking this execution until this process finished: + // 1. finished the syncing. + // 2. interrupted by a flag then it finished the current batch. + + Log.w("SCHEDULED_TASK_RUN", "sync BEGIN") + val resp2 = RustFFI.execute("sync", "") + Log.w("SCHEDULED_TASK_RUN", "sync END: $resp2") + + } else { + Log.w("SCHEDULED_TASK_RUN", "No exists wallet file END") + return Result.failure() + + } + + // save the wallet file + RPCModule.saveWallet() + + // save the background JSON file + val timeStamp = Date().time + val timeStampStr = timeStamp.toString() + val jsonBackground = "{\"batches\": \"0\", \"date\": \"$timeStampStr\"}" + RPCModule.saveBackgroundFile(jsonBackground) return Result.success() } + + private fun stopSyncingProcess() { + val resp = RustFFI.execute("syncstatus", "") + Log.d("TAG", "BGTask stopSyncingProcess - status response $resp") + + val data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) + val jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + val inProgressStr: String = jsonResp.optString("in_progress") + var inProgress: Boolean = inProgressStr.toBoolean() + + while (inProgress) { + // interrupt + val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") + Log.w("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + + Thread.sleep(500) + + val resp3 = RustFFI.execute("syncstatus", "") + Log.d("TAG", "BGTask stopSyncingProcess - status response $resp3") + + val data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) + val jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + val inProgressStr: String = jsonResp.optString("in_progress") + inProgress = inProgressStr.toBoolean() + } + + Log.w("SCHEDULED_TASK_RUN", "sync process STOPPED") + + } + + private fun walletExists() : Boolean { + // Check if a wallet already exists + val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") + return if (file.exists()) { + Log.w("SCHEDULED_TASK_RUN", "Wallet exists") + true + } else { + Log.w("SCHEDULED_TASK_RUN", "Wallet DOES NOT exist") + false + } + } } \ No newline at end of file diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt index e47dd66e6..88ba5071f 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt @@ -17,9 +17,15 @@ import kotlin.concurrent.thread class RPCModule internal constructor(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { - //companion object { - // const val TAG = "RPCModule" - //} + companion object { + fun saveWallet() { + saveWallet() + } + + fun saveBackgroundFile(json: String) { + saveBackgroundFile(json) + } + } override fun getName(): String { return "RPCModule" @@ -266,7 +272,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC promise.resolve(true) } - private fun saveWallet() { + fun saveWallet() { // Get the encoded wallet file val b64encoded = RustFFI.save() // Log.w("MAIN", b64encoded) @@ -306,6 +312,22 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC } } + fun saveBackgroundFile(json: String) { + // Log.w("MAIN", b64encoded) + + try { + val fileBytes: ByteArray = json.toByteArray() + Log.w("MAIN", "file background size: ${fileBytes.size} bytes") + + // Save file to disk + val file = MainApplication.getAppContext()?.openFileOutput("background.json", Context.MODE_PRIVATE) + file?.write(fileBytes) + file?.close() + } catch (e: IllegalArgumentException) { + Log.e("MAIN", "Couldn't save the background file") + } + } + @ReactMethod fun getLatestBlock(server: String, promise: Promise) { // Log.w("MAIN", "Initialize Light Client") From 8568830852212798edb2c88685d8fdbf20777936 Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 15 Feb 2024 10:06:56 -0700 Subject: [PATCH 03/41] fix: native background sync process - first approach done --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 63 +++++-- .../java/org/ZingoLabs/Zingo/MainActivity.kt | 29 ++- .../java/org/ZingoLabs/Zingo/RPCModule.kt | 166 ++++++++++++++---- 3 files changed, 198 insertions(+), 60 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 985a03caa..96d1c5e30 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -7,27 +7,40 @@ import android.util.Log import java.io.File import java.util.* import org.json.JSONObject +import java.io.InputStream import java.nio.charset.StandardCharsets +import com.facebook.react.bridge.ReactApplicationContext class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { override fun doWork(): Result { + val reactContext = ReactApplicationContext(MainApplication.getAppContext()) + val rpcModule = RPCModule(reactContext) + Log.w("SCHEDULED_TASK_RUN", "Task running") // checking if the wallet file exists val exits: Boolean = walletExists() if (exits) { - // stop syncing first, just in case. - stopSyncingProcess() - - // interrupt + // check the Server, because the task can run without the App. + val balance = RustFFI.execute("balance", "") + Log.w("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") + if (balance.lowercase().startsWith("error")) { + // this means this task is running with the App closed + loadWalletFile(rpcModule) + } else { + // this means the App is open, + // stop syncing first, just in case. + stopSyncingProcess() + } + + // interrupt sync to false, just in case it is true. val resp = RustFFI.execute("interrupt_sync_after_batch", "false") Log.w("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") // the task is running here blocking this execution until this process finished: // 1. finished the syncing. - // 2. interrupted by a flag then it finished the current batch. Log.w("SCHEDULED_TASK_RUN", "sync BEGIN") val resp2 = RustFFI.execute("sync", "") @@ -39,25 +52,41 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } - // save the wallet file - RPCModule.saveWallet() + // save the wallet file with the new data from the sync process + rpcModule.saveWallet() + Log.w("SCHEDULED_TASK_RUN", "wallet file SAVED") // save the background JSON file - val timeStamp = Date().time + val timeStamp = Date().time / 1000 val timeStampStr = timeStamp.toString() val jsonBackground = "{\"batches\": \"0\", \"date\": \"$timeStampStr\"}" - RPCModule.saveBackgroundFile(jsonBackground) + rpcModule.saveBackgroundFile(jsonBackground) + Log.w("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.success() } + private fun loadWalletFile(rpcModule: RPCModule) { + // I have to init from wallet file in order to do the sync + // and I need to read the settings.json to find the server & chain type + val file: InputStream = MainApplication.getAppContext()?.openFileInput("settings.json")!! + val settingsBytes = file.readBytes() + file.close() + val settingsString = settingsBytes.toString(Charsets.UTF_8) + val jsonObject = JSONObject(settingsString) + val server = jsonObject.getJSONObject("server").getString("uri") + val chainhint = jsonObject.getJSONObject("server").getString("chain_name") + Log.w("SCHEDULED_TASK_RUN", "Opening the wallet file - No App active - server: $server chain: $chainhint") + rpcModule.loadExistingWalletNative(server, chainhint) + } + private fun stopSyncingProcess() { val resp = RustFFI.execute("syncstatus", "") - Log.d("TAG", "BGTask stopSyncingProcess - status response $resp") + Log.w("SCHEDULED_TASK_RUN", "status response $resp") - val data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) - val jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) - val inProgressStr: String = jsonResp.optString("in_progress") + var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) + var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + var inProgressStr: String = jsonResp.optString("in_progress") var inProgress: Boolean = inProgressStr.toBoolean() while (inProgress) { @@ -68,11 +97,11 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W Thread.sleep(500) val resp3 = RustFFI.execute("syncstatus", "") - Log.d("TAG", "BGTask stopSyncingProcess - status response $resp3") + Log.w("SCHEDULED_TASK_RUN", "status response $resp3") - val data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) - val jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) - val inProgressStr: String = jsonResp.optString("in_progress") + data = resp.toByteArray(StandardCharsets.UTF_8) + jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + inProgressStr = jsonResp.optString("in_progress") inProgress = inProgressStr.toBoolean() } diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index f6397ffda..470db7b2e 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -1,6 +1,5 @@ package org.ZingoLabs.Zingo -import android.content.Intent import android.os.Bundle import android.util.Log import androidx.work.* @@ -13,11 +12,14 @@ class MainActivity : ReactActivity() { * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ - override fun getMainComponentName(): String? { + private val taskID = "Zingo_Processing_Task_ID" + override fun getMainComponentName(): String { return "Zingo!" } override fun onCreate(savedInstanceState: Bundle?) { Log.w("ON_CREATE", "Starting main activity") + // cancel the task if it is in execution now + cancelExecutingTask() super.onCreate(null) } @@ -29,21 +31,30 @@ class MainActivity : ReactActivity() { override fun onResume() { Log.w("ON_RESUME", "Resuming main activity - Foreground") + // cancel the task if it is in execution now + cancelExecutingTask() + // re-scheduling the task, just in case. + scheduleBackgroundTask() super.onResume() } + private fun cancelExecutingTask() { + WorkManager.getInstance(this) + .cancelUniqueWork(taskID) + } + private fun scheduleBackgroundTask() { val constraints = Constraints.Builder() + .setRequiresStorageNotLow(true) .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresCharging(true) - .setRequiresDeviceIdle(false) .build() - // PRODUCTION - next day at 3:00 am + // PRODUCTION - next day between 3:00 and 4:00 am. val currentTime = Calendar.getInstance() val targetTime = Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, 3) - set(Calendar.MINUTE, 0) + set(Calendar.MINUTE, (0..59).random()) set(Calendar.SECOND, 0) if (before(currentTime)) { add(Calendar.DATE, 1) @@ -52,18 +63,18 @@ class MainActivity : ReactActivity() { val timeDifference = targetTime.timeInMillis - currentTime.timeInMillis // DEVELOPMENT - after 5 minutes. - val timeFiveMinutes: Long = 5 + //val timeFiveMinutes: Long = 5 val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, 24, TimeUnit.HOURS) .setConstraints(constraints) - //.setInitialDelay(timeDifference, TimeUnit.MILLISECONDS) - .setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) + .setInitialDelay(timeDifference, TimeUnit.MILLISECONDS) + //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) .build() Log.w("SCHEDULING_TASK", "Enqueuing the background task - Background") WorkManager.getInstance(this) .enqueueUniquePeriodicWork( - "daily_background_sync", + taskID, ExistingPeriodicWorkPolicy.REPLACE, workRequest ) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt index 88ba5071f..2e2766e61 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt @@ -3,7 +3,6 @@ package org.ZingoLabs.Zingo import android.content.Context import android.util.Log import android.util.Base64 -import androidx.work.PeriodicWorkRequest import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod @@ -12,21 +11,10 @@ import com.facebook.react.bridge.Promise //import android.util.Log import java.io.File import java.io.InputStream -import java.util.concurrent.TimeUnit import kotlin.concurrent.thread class RPCModule internal constructor(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { - companion object { - fun saveWallet() { - saveWallet() - } - - fun saveBackgroundFile(json: String) { - saveBackgroundFile(json) - } - } - override fun getName(): String { return "RPCModule" } @@ -108,13 +96,17 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun loadExistingWallet(server: String, chainhint: String, promise: Promise) { + promise.resolve(loadExistingWalletNative(server, chainhint)) + } + + fun loadExistingWalletNative(server: String, chainhint: String): String { // Read the file val file: InputStream = MainApplication.getAppContext()?.openFileInput("wallet.dat")!! var fileBytes = file.readBytes() file.close() - val middle0w = 0 - val middle1w = 6000000 // 6_000_000 - 8 pieces + val middle0w = 0 + val middle1w = 6000000 // 6_000_000 - 8 pieces val middle2w = 12000000 val middle3w = 18000000 val middle4w = 24000000 @@ -125,34 +117,139 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC var fileb64 = StringBuilder("") if (middle8w <= middle1w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle0w, middle8w - middle0w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle0w, + middle8w - middle0w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle0w, middle1w - middle0w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle0w, + middle1w - middle0w, + Base64.NO_WRAP + ) + ) if (middle8w <= middle2w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle1w, middle8w - middle1w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle1w, + middle8w - middle1w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle1w, middle2w - middle1w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle1w, + middle2w - middle1w, + Base64.NO_WRAP + ) + ) if (middle8w <= middle3w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle2w, middle8w - middle2w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle2w, + middle8w - middle2w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle2w, middle3w - middle2w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle2w, + middle3w - middle2w, + Base64.NO_WRAP + ) + ) if (middle8w <= middle4w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle3w, middle8w - middle3w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle3w, + middle8w - middle3w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle3w, middle4w - middle3w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle3w, + middle4w - middle3w, + Base64.NO_WRAP + ) + ) if (middle8w <= middle5w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle4w, middle8w - middle4w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle4w, + middle8w - middle4w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle4w, middle5w - middle4w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle4w, + middle5w - middle4w, + Base64.NO_WRAP + ) + ) if (middle8w <= middle6w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle5w, middle8w - middle5w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle5w, + middle8w - middle5w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle5w, middle6w - middle5w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle5w, + middle6w - middle5w, + Base64.NO_WRAP + ) + ) if (middle8w <= middle7w) { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle6w, middle8w - middle6w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle6w, + middle8w - middle6w, + Base64.NO_WRAP + ) + ) } else { - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle6w, middle7w - middle6w, Base64.NO_WRAP)) - fileb64 = fileb64.append(Base64.encodeToString(fileBytes, middle7w, middle8w - middle7w, Base64.NO_WRAP)) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle6w, + middle7w - middle6w, + Base64.NO_WRAP + ) + ) + fileb64 = fileb64.append( + Base64.encodeToString( + fileBytes, + middle7w, + middle8w - middle7w, + Base64.NO_WRAP + ) + ) } } } @@ -163,13 +260,14 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - val wseed = RustFFI.initfromb64(server, - fileb64.toString(), - reactContext.applicationContext.filesDir.absolutePath, - chainhint, "true") // Log.w("MAIN", wseed) - promise.resolve(wseed) + return RustFFI.initfromb64( + server, + fileb64.toString(), + reactContext.applicationContext.filesDir.absolutePath, + chainhint, "true" + ) } @ReactMethod From a48da3bbbc0c1360968e27d88c1fb46a7e49e433 Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 15 Feb 2024 10:13:13 -0700 Subject: [PATCH 04/41] fix: typo fixed --- .../src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 96d1c5e30..d58ade65e 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -20,9 +20,9 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W Log.w("SCHEDULED_TASK_RUN", "Task running") // checking if the wallet file exists - val exits: Boolean = walletExists() + val exists: Boolean = walletExists() - if (exits) { + if (exists) { // check the Server, because the task can run without the App. val balance = RustFFI.execute("balance", "") Log.w("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") From a9166cfaee0c70610646e49a54e0cbc67ae7b91b Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 15 Feb 2024 10:23:56 -0700 Subject: [PATCH 05/41] fix: start interrupting the sync process when the App goes to background --- app/LoadedApp/LoadedApp.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/LoadedApp/LoadedApp.tsx b/app/LoadedApp/LoadedApp.tsx index b51ac94e0..822e9a1b7 100644 --- a/app/LoadedApp/LoadedApp.tsx +++ b/app/LoadedApp/LoadedApp.tsx @@ -314,6 +314,8 @@ export class LoadedAppClass extends Component Date: Thu, 15 Feb 2024 10:30:35 -0700 Subject: [PATCH 06/41] fix: init logging for rust added in background task --- .../src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index d58ade65e..b8c63e938 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -23,6 +23,8 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val exists: Boolean = walletExists() if (exists) { + RustFFI.initlogging() + // check the Server, because the task can run without the App. val balance = RustFFI.execute("balance", "") Log.w("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") From 3839be5c1f7a5b7ccc6bf240d23ccf567f3cab36 Mon Sep 17 00:00:00 2001 From: JC Date: Fri, 16 Feb 2024 11:54:30 -0700 Subject: [PATCH 07/41] fix: Android Test version 1.3.4 (132) --- android/app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index c53d08a18..496cd9225 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,9 +144,9 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 131 // Real + versionCode 132 // Real //versionCode 117 // @Test - versionName "zingo-1.3.3" // Real + versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' testBuildType System.getProperty('testBuildType', 'debug') testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' From 5d9ce2af0facc0d1e35eeee17bcdc23b78d176a9 Mon Sep 17 00:00:00 2001 From: JC Date: Sat, 17 Feb 2024 15:28:03 -0700 Subject: [PATCH 08/41] fix: adopting the same calculation from ecc for timeDifference --- android/app/build.gradle | 1 + .../java/org/ZingoLabs/Zingo/MainActivity.kt | 72 +++++++++++++++---- 2 files changed, 58 insertions(+), 15 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 496cd9225..9208642b1 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -297,6 +297,7 @@ dependencies { implementation jscFlavor } implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" + implementation "org.jetbrains.kotlinx:kotlinx-datetime:0.5.0" def work_version = "2.7.1" diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 470db7b2e..70db58325 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -1,11 +1,27 @@ package org.ZingoLabs.Zingo +import android.os.Build import android.os.Bundle import android.util.Log +import androidx.annotation.RequiresApi import androidx.work.* import com.facebook.react.ReactActivity -import java.util.concurrent.TimeUnit -import java.util.Calendar +import kotlin.random.Random +import kotlin.time.Duration +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes +import kotlin.time.DurationUnit +import kotlin.time.toDuration +import kotlin.time.toJavaDuration +import kotlinx.datetime.Clock +import kotlinx.datetime.DateTimeUnit +import kotlinx.datetime.Instant +import kotlinx.datetime.TimeZone +import kotlinx.datetime.atTime +import kotlinx.datetime.toInstant +import kotlinx.datetime.toLocalDateTime +import kotlinx.datetime.until class MainActivity : ReactActivity() { /** @@ -13,6 +29,10 @@ class MainActivity : ReactActivity() { * rendering of the component. */ private val taskID = "Zingo_Processing_Task_ID" + private val SYNC_PERIOD = 24.hours + private val SYNC_DAY_SHIFT = 1.days // Move to tomorrow + private val SYNC_START_TIME_HOURS = 3.hours // Start around 3 a.m. at night + private val SYNC_START_TIME_MINUTES = 60.minutes // Randomize with minutes until 4 a.m. override fun getMainComponentName(): String { return "Zingo!" } @@ -23,12 +43,14 @@ class MainActivity : ReactActivity() { super.onCreate(null) } + @RequiresApi(Build.VERSION_CODES.O) override fun onPause() { Log.w("ON_PAUSE", "Pausing main activity - Background") scheduleBackgroundTask() super.onPause() } + @RequiresApi(Build.VERSION_CODES.O) override fun onResume() { Log.w("ON_RESUME", "Resuming main activity - Foreground") // cancel the task if it is in execution now @@ -43,6 +65,7 @@ class MainActivity : ReactActivity() { .cancelUniqueWork(taskID) } + @RequiresApi(Build.VERSION_CODES.O) private fun scheduleBackgroundTask() { val constraints = Constraints.Builder() .setRequiresStorageNotLow(true) @@ -51,23 +74,14 @@ class MainActivity : ReactActivity() { .build() // PRODUCTION - next day between 3:00 and 4:00 am. - val currentTime = Calendar.getInstance() - val targetTime = Calendar.getInstance().apply { - set(Calendar.HOUR_OF_DAY, 3) - set(Calendar.MINUTE, (0..59).random()) - set(Calendar.SECOND, 0) - if (before(currentTime)) { - add(Calendar.DATE, 1) - } - } - val timeDifference = targetTime.timeInMillis - currentTime.timeInMillis + val targetTimeDiff = calculateTargetTimeDifference() // DEVELOPMENT - after 5 minutes. //val timeFiveMinutes: Long = 5 - val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, 24, TimeUnit.HOURS) + val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, SYNC_PERIOD.toJavaDuration()) .setConstraints(constraints) - .setInitialDelay(timeDifference, TimeUnit.MILLISECONDS) + .setInitialDelay(targetTimeDiff.toJavaDuration()) //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) .build() @@ -75,8 +89,36 @@ class MainActivity : ReactActivity() { WorkManager.getInstance(this) .enqueueUniquePeriodicWork( taskID, - ExistingPeriodicWorkPolicy.REPLACE, + ExistingPeriodicWorkPolicy.KEEP, workRequest ) } + + private fun calculateTargetTimeDifference(): Duration { + val currentTimeZone: TimeZone = TimeZone.currentSystemDefault() + + val now: Instant = Clock.System.now() + + val targetTime = + now + .plus(SYNC_DAY_SHIFT) + .toLocalDateTime(currentTimeZone) + .date + .atTime( + hour = SYNC_START_TIME_HOURS.inWholeHours.toInt(), + // Even though the WorkManager will trigger the work approximately at the set time, it's + // better to randomize time in 3-4 a.m. This generates a number between 0 (inclusive) and 60 + // (exclusive) + minute = Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) + ) + + val targetTimeTime = targetTime.time + Log.w("SCHEDULING_TASK", "calculated target time $targetTimeTime") + + return now.until( + other = targetTime.toInstant(currentTimeZone), + unit = DateTimeUnit.MILLISECOND, + timeZone = currentTimeZone + ).toDuration(DurationUnit.MILLISECONDS) + } } \ No newline at end of file From 3ba063178698a547d20b66ef1a045a96bb113bc9 Mon Sep 17 00:00:00 2001 From: JC Date: Sun, 18 Feb 2024 08:34:00 -0700 Subject: [PATCH 09/41] fix: Android Test version 1.3.4 (133) --- android/app/build.gradle | 2 +- android/build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 9208642b1..c5444b419 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 132 // Real + versionCode 133 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/android/build.gradle b/android/build.gradle index 6cae882ac..12b8eed52 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -7,7 +7,7 @@ buildscript { compileSdkVersion = 33 targetSdkVersion = 33 ndkVersion = "23.2.8568313" - kotlinVersion = '1.6.21' + kotlinVersion = '1.9.0' } repositories { google() From 5bdecf50640f81ca8fd1065410f1552b59bc36b5 Mon Sep 17 00:00:00 2001 From: JC Date: Sun, 18 Feb 2024 14:22:37 -0700 Subject: [PATCH 10/41] fix: change Log.w to Log.d --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 30 ++++++------- .../java/org/ZingoLabs/Zingo/MainActivity.kt | 10 ++--- .../java/org/ZingoLabs/Zingo/RPCModule.kt | 44 +++++++++---------- 3 files changed, 42 insertions(+), 42 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index b8c63e938..cc1f9634f 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -17,7 +17,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val reactContext = ReactApplicationContext(MainApplication.getAppContext()) val rpcModule = RPCModule(reactContext) - Log.w("SCHEDULED_TASK_RUN", "Task running") + Log.d("SCHEDULED_TASK_RUN", "Task running") // checking if the wallet file exists val exists: Boolean = walletExists() @@ -27,7 +27,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // check the Server, because the task can run without the App. val balance = RustFFI.execute("balance", "") - Log.w("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") + Log.d("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") if (balance.lowercase().startsWith("error")) { // this means this task is running with the App closed loadWalletFile(rpcModule) @@ -39,31 +39,31 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // interrupt sync to false, just in case it is true. val resp = RustFFI.execute("interrupt_sync_after_batch", "false") - Log.w("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") + Log.d("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") // the task is running here blocking this execution until this process finished: // 1. finished the syncing. - Log.w("SCHEDULED_TASK_RUN", "sync BEGIN") + Log.d("SCHEDULED_TASK_RUN", "sync BEGIN") val resp2 = RustFFI.execute("sync", "") - Log.w("SCHEDULED_TASK_RUN", "sync END: $resp2") + Log.d("SCHEDULED_TASK_RUN", "sync END: $resp2") } else { - Log.w("SCHEDULED_TASK_RUN", "No exists wallet file END") + Log.d("SCHEDULED_TASK_RUN", "No exists wallet file END") return Result.failure() } // save the wallet file with the new data from the sync process rpcModule.saveWallet() - Log.w("SCHEDULED_TASK_RUN", "wallet file SAVED") + Log.d("SCHEDULED_TASK_RUN", "wallet file SAVED") // save the background JSON file val timeStamp = Date().time / 1000 val timeStampStr = timeStamp.toString() val jsonBackground = "{\"batches\": \"0\", \"date\": \"$timeStampStr\"}" rpcModule.saveBackgroundFile(jsonBackground) - Log.w("SCHEDULED_TASK_RUN", "background json file SAVED") + Log.d("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.success() } @@ -78,13 +78,13 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val jsonObject = JSONObject(settingsString) val server = jsonObject.getJSONObject("server").getString("uri") val chainhint = jsonObject.getJSONObject("server").getString("chain_name") - Log.w("SCHEDULED_TASK_RUN", "Opening the wallet file - No App active - server: $server chain: $chainhint") + Log.d("SCHEDULED_TASK_RUN", "Opening the wallet file - No App active - server: $server chain: $chainhint") rpcModule.loadExistingWalletNative(server, chainhint) } private fun stopSyncingProcess() { val resp = RustFFI.execute("syncstatus", "") - Log.w("SCHEDULED_TASK_RUN", "status response $resp") + Log.d("SCHEDULED_TASK_RUN", "status response $resp") var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) @@ -94,12 +94,12 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W while (inProgress) { // interrupt val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") - Log.w("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + Log.d("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") Thread.sleep(500) val resp3 = RustFFI.execute("syncstatus", "") - Log.w("SCHEDULED_TASK_RUN", "status response $resp3") + Log.d("SCHEDULED_TASK_RUN", "status response $resp3") data = resp.toByteArray(StandardCharsets.UTF_8) jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) @@ -107,7 +107,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W inProgress = inProgressStr.toBoolean() } - Log.w("SCHEDULED_TASK_RUN", "sync process STOPPED") + Log.d("SCHEDULED_TASK_RUN", "sync process STOPPED") } @@ -115,10 +115,10 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") return if (file.exists()) { - Log.w("SCHEDULED_TASK_RUN", "Wallet exists") + Log.d("SCHEDULED_TASK_RUN", "Wallet exists") true } else { - Log.w("SCHEDULED_TASK_RUN", "Wallet DOES NOT exist") + Log.d("SCHEDULED_TASK_RUN", "Wallet DOES NOT exist") false } } diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 70db58325..0a3f1d6e2 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -37,7 +37,7 @@ class MainActivity : ReactActivity() { return "Zingo!" } override fun onCreate(savedInstanceState: Bundle?) { - Log.w("ON_CREATE", "Starting main activity") + Log.d("ON_CREATE", "Starting main activity") // cancel the task if it is in execution now cancelExecutingTask() super.onCreate(null) @@ -45,14 +45,14 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onPause() { - Log.w("ON_PAUSE", "Pausing main activity - Background") + Log.d("ON_PAUSE", "Pausing main activity - Background") scheduleBackgroundTask() super.onPause() } @RequiresApi(Build.VERSION_CODES.O) override fun onResume() { - Log.w("ON_RESUME", "Resuming main activity - Foreground") + Log.d("ON_RESUME", "Resuming main activity - Foreground") // cancel the task if it is in execution now cancelExecutingTask() // re-scheduling the task, just in case. @@ -85,7 +85,7 @@ class MainActivity : ReactActivity() { //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) .build() - Log.w("SCHEDULING_TASK", "Enqueuing the background task - Background") + Log.d("SCHEDULING_TASK", "Enqueuing the background task - Background") WorkManager.getInstance(this) .enqueueUniquePeriodicWork( taskID, @@ -113,7 +113,7 @@ class MainActivity : ReactActivity() { ) val targetTimeTime = targetTime.time - Log.w("SCHEDULING_TASK", "calculated target time $targetTimeTime") + Log.d("SCHEDULING_TASK", "calculated target time $targetTimeTime") return now.until( other = targetTime.toInstant(currentTimeZone), diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt index 2e2766e61..79717daff 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt @@ -24,10 +24,10 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") if (file.exists()) { - // Log.w("MAIN", "Wallet exists") + // Log.d("MAIN", "Wallet exists") promise.resolve(true) } else { - // Log.w("MAIN", "Wallet DOES NOT exist") + // Log.d("MAIN", "Wallet DOES NOT exist") promise.resolve(false) } } @@ -37,23 +37,23 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC // Check if a wallet backup already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.backup.dat") if (file.exists()) { - // Log.w("MAIN", "Wallet backup exists") + // Log.d("MAIN", "Wallet backup exists") promise.resolve(true) } else { - // Log.w("MAIN", "Wallet backup DOES NOT exist") + // Log.d("MAIN", "Wallet backup DOES NOT exist") promise.resolve(false) } } @ReactMethod fun createNewWallet(server: String, chainhint: String, promise: Promise) { - // Log.w("MAIN", "Creating new wallet") + // Log.d("MAIN", "Creating new wallet") RustFFI.initlogging() // Create a seed val seed = RustFFI.initnew(server, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") - // Log.w("MAIN-Seed", seed) + // Log.d("MAIN-Seed", seed) if (!seed.startsWith("Error")) { saveWallet() @@ -64,12 +64,12 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun restoreWalletFromSeed(seed: String, birthday: String, server: String, chainhint: String, promise: Promise) { - // Log.w("MAIN", "Restoring wallet with seed $seed") + // Log.d("MAIN", "Restoring wallet with seed $seed") RustFFI.initlogging() val rseed = RustFFI.initfromseed(server, seed, birthday, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") - // Log.w("MAIN", rseed) + // Log.d("MAIN", rseed) if (!rseed.startsWith("Error")) { saveWallet() @@ -80,12 +80,12 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun restoreWalletFromUfvk(ufvk: String, birthday: String, server: String, chainhint: String, promise: Promise) { - // Log.w("MAIN", "Restoring wallet with ufvk $ufvk") + // Log.d("MAIN", "Restoring wallet with ufvk $ufvk") RustFFI.initlogging() val rufvk = RustFFI.initfromufvk(server, ufvk, birthday, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") - // Log.w("MAIN", rufvk) + // Log.d("MAIN", rufvk) if (!rufvk.startsWith("Error")) { saveWallet() @@ -260,7 +260,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - // Log.w("MAIN", wseed) + // Log.d("MAIN", wseed) return RustFFI.initfromb64( server, @@ -329,9 +329,9 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - // Log.w("send", "Trying to send $sendJSON") + // Log.d("send", "Trying to send $sendJSON") val result = RustFFI.execute("send", sendJSON) - // Log.w("send", "Send Result: $result") + // Log.d("send", "Send Result: $result") promise.resolve(result) } @@ -343,9 +343,9 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - // Log.w("execute", "Executing $cmd with $args") + // Log.d("execute", "Executing $cmd with $args") val resp = RustFFI.execute(cmd, args) - // Log.w("execute", "Response to $cmd : $resp") + // Log.d("execute", "Response to $cmd : $resp") // And save it if it was a sync if (cmd == "sync" && !resp.startsWith("Error")) { @@ -373,11 +373,11 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC fun saveWallet() { // Get the encoded wallet file val b64encoded = RustFFI.save() - // Log.w("MAIN", b64encoded) + // Log.d("MAIN", b64encoded) try { val fileBytes = Base64.decode(b64encoded, Base64.NO_WRAP) - Log.w("MAIN", "file size: ${fileBytes.size} bytes") + Log.d("MAIN", "file size: ${fileBytes.size} bytes") // Save file to disk val file = MainApplication.getAppContext()?.openFileOutput("wallet.dat", Context.MODE_PRIVATE) @@ -395,11 +395,11 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC val fileRead = MainApplication.getAppContext()!!.openFileInput("wallet.dat") val fileBytes = fileRead.readBytes() // val fileb64 = Base64.encodeToString(fileBytes, Base64.NO_WRAP) - // Log.w("MAIN", b64encoded) + // Log.d("MAIN", b64encoded) try { // val fileBytes = Base64.decode(b64encoded, Base64.NO_WRAP) - // Log.w("MAIN", "file size${fileBytes.size}") + // Log.d("MAIN", "file size${fileBytes.size}") // Save file to disk val file = MainApplication.getAppContext()?.openFileOutput("wallet.backup.dat", Context.MODE_PRIVATE) @@ -411,11 +411,11 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC } fun saveBackgroundFile(json: String) { - // Log.w("MAIN", b64encoded) + // Log.d("MAIN", b64encoded) try { val fileBytes: ByteArray = json.toByteArray() - Log.w("MAIN", "file background size: ${fileBytes.size} bytes") + Log.d("MAIN", "file background size: ${fileBytes.size} bytes") // Save file to disk val file = MainApplication.getAppContext()?.openFileOutput("background.json", Context.MODE_PRIVATE) @@ -428,7 +428,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun getLatestBlock(server: String, promise: Promise) { - // Log.w("MAIN", "Initialize Light Client") + // Log.d("MAIN", "Initialize Light Client") RustFFI.initlogging() From 8e0b795f4f693b358b488fac3c732e05173a2d2c Mon Sep 17 00:00:00 2001 From: JC Date: Sun, 18 Feb 2024 14:39:20 -0700 Subject: [PATCH 11/41] fix: format fix --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index cc1f9634f..50eb60aab 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -24,7 +24,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W if (exists) { RustFFI.initlogging() - + // check the Server, because the task can run without the App. val balance = RustFFI.execute("balance", "") Log.d("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") @@ -71,15 +71,19 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W private fun loadWalletFile(rpcModule: RPCModule) { // I have to init from wallet file in order to do the sync // and I need to read the settings.json to find the server & chain type - val file: InputStream = MainApplication.getAppContext()?.openFileInput("settings.json")!! - val settingsBytes = file.readBytes() - file.close() - val settingsString = settingsBytes.toString(Charsets.UTF_8) - val jsonObject = JSONObject(settingsString) - val server = jsonObject.getJSONObject("server").getString("uri") - val chainhint = jsonObject.getJSONObject("server").getString("chain_name") - Log.d("SCHEDULED_TASK_RUN", "Opening the wallet file - No App active - server: $server chain: $chainhint") - rpcModule.loadExistingWalletNative(server, chainhint) + MainApplication.getAppContext()?.openFileInput("settings.json")?.use { file -> + val settingsBytes = file.readBytes() + file.close() + val settingsString = settingsBytes.toString(Charsets.UTF_8) + val jsonObject = JSONObject(settingsString) + val server = jsonObject.getJSONObject("server").getString("uri") + val chainhint = jsonObject.getJSONObject("server").getString("chain_name") + Log.d( + "SCHEDULED_TASK_RUN", + "Opening the wallet file - No App active - server: $server chain: $chainhint" + ) + rpcModule.loadExistingWalletNative(server, chainhint) + } } private fun stopSyncingProcess() { @@ -111,7 +115,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } - private fun walletExists() : Boolean { + private fun walletExists(): Boolean { // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") return if (file.exists()) { From 4668152d0764e51a955fbbe8becbe6ae95b22708 Mon Sep 17 00:00:00 2001 From: JC Date: Mon, 19 Feb 2024 08:10:28 -0700 Subject: [PATCH 12/41] fix: using Log.i instead --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 30 ++++++------- .../java/org/ZingoLabs/Zingo/MainActivity.kt | 10 ++--- .../java/org/ZingoLabs/Zingo/RPCModule.kt | 44 +++++++++---------- 3 files changed, 42 insertions(+), 42 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 50eb60aab..f40a4467d 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -17,7 +17,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val reactContext = ReactApplicationContext(MainApplication.getAppContext()) val rpcModule = RPCModule(reactContext) - Log.d("SCHEDULED_TASK_RUN", "Task running") + Log.i("SCHEDULED_TASK_RUN", "Task running") // checking if the wallet file exists val exists: Boolean = walletExists() @@ -27,7 +27,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // check the Server, because the task can run without the App. val balance = RustFFI.execute("balance", "") - Log.d("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") + Log.i("SCHEDULED_TASK_RUN", "Testing if server is active: $balance") if (balance.lowercase().startsWith("error")) { // this means this task is running with the App closed loadWalletFile(rpcModule) @@ -39,31 +39,31 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // interrupt sync to false, just in case it is true. val resp = RustFFI.execute("interrupt_sync_after_batch", "false") - Log.d("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") + Log.i("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") // the task is running here blocking this execution until this process finished: // 1. finished the syncing. - Log.d("SCHEDULED_TASK_RUN", "sync BEGIN") + Log.i("SCHEDULED_TASK_RUN", "sync BEGIN") val resp2 = RustFFI.execute("sync", "") - Log.d("SCHEDULED_TASK_RUN", "sync END: $resp2") + Log.i("SCHEDULED_TASK_RUN", "sync END: $resp2") } else { - Log.d("SCHEDULED_TASK_RUN", "No exists wallet file END") + Log.i("SCHEDULED_TASK_RUN", "No exists wallet file END") return Result.failure() } // save the wallet file with the new data from the sync process rpcModule.saveWallet() - Log.d("SCHEDULED_TASK_RUN", "wallet file SAVED") + Log.i("SCHEDULED_TASK_RUN", "wallet file SAVED") // save the background JSON file val timeStamp = Date().time / 1000 val timeStampStr = timeStamp.toString() val jsonBackground = "{\"batches\": \"0\", \"date\": \"$timeStampStr\"}" rpcModule.saveBackgroundFile(jsonBackground) - Log.d("SCHEDULED_TASK_RUN", "background json file SAVED") + Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.success() } @@ -78,7 +78,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val jsonObject = JSONObject(settingsString) val server = jsonObject.getJSONObject("server").getString("uri") val chainhint = jsonObject.getJSONObject("server").getString("chain_name") - Log.d( + Log.i( "SCHEDULED_TASK_RUN", "Opening the wallet file - No App active - server: $server chain: $chainhint" ) @@ -88,7 +88,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W private fun stopSyncingProcess() { val resp = RustFFI.execute("syncstatus", "") - Log.d("SCHEDULED_TASK_RUN", "status response $resp") + Log.i("SCHEDULED_TASK_RUN", "status response $resp") var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) @@ -98,12 +98,12 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W while (inProgress) { // interrupt val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") - Log.d("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") Thread.sleep(500) val resp3 = RustFFI.execute("syncstatus", "") - Log.d("SCHEDULED_TASK_RUN", "status response $resp3") + Log.i("SCHEDULED_TASK_RUN", "status response $resp3") data = resp.toByteArray(StandardCharsets.UTF_8) jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) @@ -111,7 +111,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W inProgress = inProgressStr.toBoolean() } - Log.d("SCHEDULED_TASK_RUN", "sync process STOPPED") + Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED") } @@ -119,10 +119,10 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") return if (file.exists()) { - Log.d("SCHEDULED_TASK_RUN", "Wallet exists") + Log.i("SCHEDULED_TASK_RUN", "Wallet exists") true } else { - Log.d("SCHEDULED_TASK_RUN", "Wallet DOES NOT exist") + Log.i("SCHEDULED_TASK_RUN", "Wallet DOES NOT exist") false } } diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 0a3f1d6e2..8ceb1aa6a 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -37,7 +37,7 @@ class MainActivity : ReactActivity() { return "Zingo!" } override fun onCreate(savedInstanceState: Bundle?) { - Log.d("ON_CREATE", "Starting main activity") + Log.i("ON_CREATE", "Starting main activity") // cancel the task if it is in execution now cancelExecutingTask() super.onCreate(null) @@ -45,14 +45,14 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onPause() { - Log.d("ON_PAUSE", "Pausing main activity - Background") + Log.i("ON_PAUSE", "Pausing main activity - Background") scheduleBackgroundTask() super.onPause() } @RequiresApi(Build.VERSION_CODES.O) override fun onResume() { - Log.d("ON_RESUME", "Resuming main activity - Foreground") + Log.i("ON_RESUME", "Resuming main activity - Foreground") // cancel the task if it is in execution now cancelExecutingTask() // re-scheduling the task, just in case. @@ -85,7 +85,7 @@ class MainActivity : ReactActivity() { //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) .build() - Log.d("SCHEDULING_TASK", "Enqueuing the background task - Background") + Log.i("SCHEDULING_TASK", "Enqueuing the background task - Background") WorkManager.getInstance(this) .enqueueUniquePeriodicWork( taskID, @@ -113,7 +113,7 @@ class MainActivity : ReactActivity() { ) val targetTimeTime = targetTime.time - Log.d("SCHEDULING_TASK", "calculated target time $targetTimeTime") + Log.i("SCHEDULING_TASK", "calculated target time $targetTimeTime") return now.until( other = targetTime.toInstant(currentTimeZone), diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt index 79717daff..29ea405ad 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt @@ -24,10 +24,10 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") if (file.exists()) { - // Log.d("MAIN", "Wallet exists") + // Log.i("MAIN", "Wallet exists") promise.resolve(true) } else { - // Log.d("MAIN", "Wallet DOES NOT exist") + // Log.i("MAIN", "Wallet DOES NOT exist") promise.resolve(false) } } @@ -37,23 +37,23 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC // Check if a wallet backup already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.backup.dat") if (file.exists()) { - // Log.d("MAIN", "Wallet backup exists") + // Log.i("MAIN", "Wallet backup exists") promise.resolve(true) } else { - // Log.d("MAIN", "Wallet backup DOES NOT exist") + // Log.i("MAIN", "Wallet backup DOES NOT exist") promise.resolve(false) } } @ReactMethod fun createNewWallet(server: String, chainhint: String, promise: Promise) { - // Log.d("MAIN", "Creating new wallet") + // Log.i("MAIN", "Creating new wallet") RustFFI.initlogging() // Create a seed val seed = RustFFI.initnew(server, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") - // Log.d("MAIN-Seed", seed) + // Log.i("MAIN-Seed", seed) if (!seed.startsWith("Error")) { saveWallet() @@ -64,12 +64,12 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun restoreWalletFromSeed(seed: String, birthday: String, server: String, chainhint: String, promise: Promise) { - // Log.d("MAIN", "Restoring wallet with seed $seed") + // Log.i("MAIN", "Restoring wallet with seed $seed") RustFFI.initlogging() val rseed = RustFFI.initfromseed(server, seed, birthday, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") - // Log.d("MAIN", rseed) + // Log.i("MAIN", rseed) if (!rseed.startsWith("Error")) { saveWallet() @@ -80,12 +80,12 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun restoreWalletFromUfvk(ufvk: String, birthday: String, server: String, chainhint: String, promise: Promise) { - // Log.d("MAIN", "Restoring wallet with ufvk $ufvk") + // Log.i("MAIN", "Restoring wallet with ufvk $ufvk") RustFFI.initlogging() val rufvk = RustFFI.initfromufvk(server, ufvk, birthday, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") - // Log.d("MAIN", rufvk) + // Log.i("MAIN", rufvk) if (!rufvk.startsWith("Error")) { saveWallet() @@ -260,7 +260,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - // Log.d("MAIN", wseed) + // Log.i("MAIN", wseed) return RustFFI.initfromb64( server, @@ -329,9 +329,9 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - // Log.d("send", "Trying to send $sendJSON") + // Log.i("send", "Trying to send $sendJSON") val result = RustFFI.execute("send", sendJSON) - // Log.d("send", "Send Result: $result") + // Log.i("send", "Send Result: $result") promise.resolve(result) } @@ -343,9 +343,9 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC RustFFI.initlogging() - // Log.d("execute", "Executing $cmd with $args") + // Log.i("execute", "Executing $cmd with $args") val resp = RustFFI.execute(cmd, args) - // Log.d("execute", "Response to $cmd : $resp") + // Log.i("execute", "Response to $cmd : $resp") // And save it if it was a sync if (cmd == "sync" && !resp.startsWith("Error")) { @@ -373,11 +373,11 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC fun saveWallet() { // Get the encoded wallet file val b64encoded = RustFFI.save() - // Log.d("MAIN", b64encoded) + // Log.i("MAIN", b64encoded) try { val fileBytes = Base64.decode(b64encoded, Base64.NO_WRAP) - Log.d("MAIN", "file size: ${fileBytes.size} bytes") + Log.i("MAIN", "file size: ${fileBytes.size} bytes") // Save file to disk val file = MainApplication.getAppContext()?.openFileOutput("wallet.dat", Context.MODE_PRIVATE) @@ -395,11 +395,11 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC val fileRead = MainApplication.getAppContext()!!.openFileInput("wallet.dat") val fileBytes = fileRead.readBytes() // val fileb64 = Base64.encodeToString(fileBytes, Base64.NO_WRAP) - // Log.d("MAIN", b64encoded) + // Log.i("MAIN", b64encoded) try { // val fileBytes = Base64.decode(b64encoded, Base64.NO_WRAP) - // Log.d("MAIN", "file size${fileBytes.size}") + // Log.i("MAIN", "file size${fileBytes.size}") // Save file to disk val file = MainApplication.getAppContext()?.openFileOutput("wallet.backup.dat", Context.MODE_PRIVATE) @@ -411,11 +411,11 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC } fun saveBackgroundFile(json: String) { - // Log.d("MAIN", b64encoded) + // Log.i("MAIN", b64encoded) try { val fileBytes: ByteArray = json.toByteArray() - Log.d("MAIN", "file background size: ${fileBytes.size} bytes") + Log.i("MAIN", "file background size: ${fileBytes.size} bytes") // Save file to disk val file = MainApplication.getAppContext()?.openFileOutput("background.json", Context.MODE_PRIVATE) @@ -428,7 +428,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC @ReactMethod fun getLatestBlock(server: String, promise: Promise) { - // Log.d("MAIN", "Initialize Light Client") + // Log.i("MAIN", "Initialize Light Client") RustFFI.initlogging() From 7c33e1599c691086f4ffed70b9667b1db768fc3b Mon Sep 17 00:00:00 2001 From: JC Date: Mon, 19 Feb 2024 15:05:04 -0700 Subject: [PATCH 13/41] fix: adjusting BS in Android --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 74 +++++++++++-------- .../java/org/ZingoLabs/Zingo/MainActivity.kt | 28 +++++-- .../java/org/ZingoLabs/Zingo/RPCModule.kt | 8 +- package.json | 3 +- 4 files changed, 69 insertions(+), 44 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index f40a4467d..3f105fed3 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -7,7 +7,6 @@ import android.util.Log import java.io.File import java.util.* import org.json.JSONObject -import java.io.InputStream import java.nio.charset.StandardCharsets import com.facebook.react.bridge.ReactApplicationContext @@ -34,7 +33,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } else { // this means the App is open, // stop syncing first, just in case. - stopSyncingProcess() + BSCompanion.stopSyncingProcess() } // interrupt sync to false, just in case it is true. @@ -86,35 +85,6 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } } - private fun stopSyncingProcess() { - val resp = RustFFI.execute("syncstatus", "") - Log.i("SCHEDULED_TASK_RUN", "status response $resp") - - var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) - var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) - var inProgressStr: String = jsonResp.optString("in_progress") - var inProgress: Boolean = inProgressStr.toBoolean() - - while (inProgress) { - // interrupt - val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") - Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") - - Thread.sleep(500) - - val resp3 = RustFFI.execute("syncstatus", "") - Log.i("SCHEDULED_TASK_RUN", "status response $resp3") - - data = resp.toByteArray(StandardCharsets.UTF_8) - jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) - inProgressStr = jsonResp.optString("in_progress") - inProgress = inProgressStr.toBoolean() - } - - Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED") - - } - private fun walletExists(): Boolean { // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") @@ -126,4 +96,46 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W false } } +} + +class BSCompanion { + companion object { + fun stopSyncingProcess() { + val resp = RustFFI.execute("syncstatus", "") + Log.i("SCHEDULED_TASK_RUN", "status response $resp") + + if (resp.lowercase().startsWith("error")) { + Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED - no lightwalletd likely") + return + } + + var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) + var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + var inProgressStr: String = jsonResp.optString("in_progress") + var inProgress: Boolean = inProgressStr.toBoolean() + + Log.i("SCHEDULED_TASK_RUN", "in progress value $inProgress") + + while (inProgress) { + // interrupt + val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") + Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + + Thread.sleep(500) + + val resp3 = RustFFI.execute("syncstatus", "") + Log.i("SCHEDULED_TASK_RUN", "status response $resp3") + + data = resp.toByteArray(StandardCharsets.UTF_8) + jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + inProgressStr = jsonResp.optString("in_progress") + inProgress = inProgressStr.toBoolean() + + Log.i("SCHEDULED_TASK_RUN", "in progress value $inProgress") + } + + Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED") + + } + } } \ No newline at end of file diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 8ceb1aa6a..1c87f3bb4 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -33,19 +33,22 @@ class MainActivity : ReactActivity() { private val SYNC_DAY_SHIFT = 1.days // Move to tomorrow private val SYNC_START_TIME_HOURS = 3.hours // Start around 3 a.m. at night private val SYNC_START_TIME_MINUTES = 60.minutes // Randomize with minutes until 4 a.m. + private var isStarting = true override fun getMainComponentName(): String { return "Zingo!" } override fun onCreate(savedInstanceState: Bundle?) { Log.i("ON_CREATE", "Starting main activity") - // cancel the task if it is in execution now - cancelExecutingTask() super.onCreate(null) } @RequiresApi(Build.VERSION_CODES.O) override fun onPause() { Log.i("ON_PAUSE", "Pausing main activity - Background") + // cancel the task if it is in execution now + BSCompanion.stopSyncingProcess() + cancelExecutingTask() + // scheduling the task. scheduleBackgroundTask() super.onPause() } @@ -53,14 +56,20 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onResume() { Log.i("ON_RESUME", "Resuming main activity - Foreground") - // cancel the task if it is in execution now - cancelExecutingTask() - // re-scheduling the task, just in case. - scheduleBackgroundTask() + if (isStarting) { + isStarting = false + } else { + // cancel the task if it is in execution now + BSCompanion.stopSyncingProcess() + cancelExecutingTask() + // re-scheduling the task, just in case. + scheduleBackgroundTask() + } super.onResume() } private fun cancelExecutingTask() { + Log.i("SCHEDULING_TASK", "Cancel background Task") WorkManager.getInstance(this) .cancelUniqueWork(taskID) } @@ -76,6 +85,8 @@ class MainActivity : ReactActivity() { // PRODUCTION - next day between 3:00 and 4:00 am. val targetTimeDiff = calculateTargetTimeDifference() + Log.i("SCHEDULING_TASK", "calculated target time DIFF $targetTimeDiff") + // DEVELOPMENT - after 5 minutes. //val timeFiveMinutes: Long = 5 @@ -89,7 +100,7 @@ class MainActivity : ReactActivity() { WorkManager.getInstance(this) .enqueueUniquePeriodicWork( taskID, - ExistingPeriodicWorkPolicy.KEEP, + ExistingPeriodicWorkPolicy.REPLACE, workRequest ) } @@ -113,7 +124,8 @@ class MainActivity : ReactActivity() { ) val targetTimeTime = targetTime.time - Log.i("SCHEDULING_TASK", "calculated target time $targetTimeTime") + val targetTimeDate = targetTime.date + Log.i("SCHEDULING_TASK", "calculated target time $targetTimeTime and date $targetTimeDate") return now.until( other = targetTime.toInstant(currentTimeZone), diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt index 29ea405ad..bb130285e 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/RPCModule.kt @@ -55,7 +55,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC val seed = RustFFI.initnew(server, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") // Log.i("MAIN-Seed", seed) - if (!seed.startsWith("Error")) { + if (!seed.lowercase().startsWith("error")) { saveWallet() } @@ -71,7 +71,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC val rseed = RustFFI.initfromseed(server, seed, birthday, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") // Log.i("MAIN", rseed) - if (!rseed.startsWith("Error")) { + if (!rseed.lowercase().startsWith("Error")) { saveWallet() } @@ -87,7 +87,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC val rufvk = RustFFI.initfromufvk(server, ufvk, birthday, reactContext.applicationContext.filesDir.absolutePath, chainhint, "true") // Log.i("MAIN", rufvk) - if (!rufvk.startsWith("Error")) { + if (!rufvk.lowercase().startsWith("Error")) { saveWallet() } @@ -348,7 +348,7 @@ class RPCModule internal constructor(private val reactContext: ReactApplicationC // Log.i("execute", "Response to $cmd : $resp") // And save it if it was a sync - if (cmd == "sync" && !resp.startsWith("Error")) { + if (cmd == "sync" && !resp.lowercase().startsWith("Error")) { saveWallet() } diff --git a/package.json b/package.json index d1004c2da..a064eec1c 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "lint": "eslint . --fix --ext .js,.jsx,.ts,.tsx", "coverage": "jest --coverage", "postinstall": "patch-package", - "build:bundle": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && rimraf --glob android/app/src/main/res/drawable* && cd android && ./gradlew assembleRelease -PsplitApk=true && cd .." + "build:bundle": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && rimraf --glob android/app/src/main/res/drawable* && cd android && ./gradlew assembleRelease -PsplitApk=true && cd ..", + "bundle": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && rimraf --glob android/app/src/main/res/drawable*" }, "dependencies": { "@fortawesome/fontawesome-svg-core": "^6.2.0", From 2017d4d948a6f1ce2b31d622e84cddd81380f015 Mon Sep 17 00:00:00 2001 From: JC Date: Mon, 19 Feb 2024 15:07:38 -0700 Subject: [PATCH 14/41] fix: Android Test version 1.3.4 (134) --- android/app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index c5444b419..f29b4d68f 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 133 // Real + versionCode 134 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' From 0a07a2c6436a3c2ecf565251b3b7ffd862d1f5e1 Mon Sep 17 00:00:00 2001 From: JC Date: Mon, 19 Feb 2024 20:30:03 -0700 Subject: [PATCH 15/41] fix: reverting stop syncing in mainactivity --- .../app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 1c87f3bb4..ac68ace48 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -34,6 +34,7 @@ class MainActivity : ReactActivity() { private val SYNC_START_TIME_HOURS = 3.hours // Start around 3 a.m. at night private val SYNC_START_TIME_MINUTES = 60.minutes // Randomize with minutes until 4 a.m. private var isStarting = true + override fun getMainComponentName(): String { return "Zingo!" } @@ -45,10 +46,6 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onPause() { Log.i("ON_PAUSE", "Pausing main activity - Background") - // cancel the task if it is in execution now - BSCompanion.stopSyncingProcess() - cancelExecutingTask() - // scheduling the task. scheduleBackgroundTask() super.onPause() } @@ -60,7 +57,6 @@ class MainActivity : ReactActivity() { isStarting = false } else { // cancel the task if it is in execution now - BSCompanion.stopSyncingProcess() cancelExecutingTask() // re-scheduling the task, just in case. scheduleBackgroundTask() From 55144f3d068b30bdc20b7dc080a22c60142d69d6 Mon Sep 17 00:00:00 2001 From: JC Date: Tue, 20 Feb 2024 08:59:56 -0700 Subject: [PATCH 16/41] fix: not re-scheduling when go to foreground --- .../org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 1 + .../main/java/org/ZingoLabs/Zingo/MainActivity.kt | 13 +++---------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 3f105fed3..a472999bd 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -121,6 +121,7 @@ class BSCompanion { val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + // blocking the thread for 0.5 seconds. Thread.sleep(500) val resp3 = RustFFI.execute("syncstatus", "") diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index ac68ace48..477c85a15 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -33,7 +33,6 @@ class MainActivity : ReactActivity() { private val SYNC_DAY_SHIFT = 1.days // Move to tomorrow private val SYNC_START_TIME_HOURS = 3.hours // Start around 3 a.m. at night private val SYNC_START_TIME_MINUTES = 60.minutes // Randomize with minutes until 4 a.m. - private var isStarting = true override fun getMainComponentName(): String { return "Zingo!" @@ -53,14 +52,8 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onResume() { Log.i("ON_RESUME", "Resuming main activity - Foreground") - if (isStarting) { - isStarting = false - } else { - // cancel the task if it is in execution now - cancelExecutingTask() - // re-scheduling the task, just in case. - scheduleBackgroundTask() - } + // cancel the task if it is in execution now + cancelExecutingTask() super.onResume() } @@ -73,7 +66,7 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) private fun scheduleBackgroundTask() { val constraints = Constraints.Builder() - .setRequiresStorageNotLow(true) + .setRequiresStorageNotLow(false) // less restricted .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresCharging(true) .build() From db2d964a7d300134af58555d0b5d2c7a7fe51d31 Mon Sep 17 00:00:00 2001 From: JC Date: Tue, 20 Feb 2024 09:01:59 -0700 Subject: [PATCH 17/41] fix: Android Test version 1.3.4 (135) --- android/app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index f29b4d68f..965cf3e14 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 134 // Real + versionCode 135 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' From 53dd7525e2ccde0e3017d5dd4a2c4ba06de78485 Mon Sep 17 00:00:00 2001 From: JC Date: Tue, 20 Feb 2024 15:19:12 -0700 Subject: [PATCH 18/41] fix: Android Test version 1.3.4 (137) --- android/app/build.gradle | 2 +- .../java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 965cf3e14..b03633c8a 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 135 // Real + versionCode 137 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index a472999bd..a3686b08d 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -18,6 +18,13 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W Log.i("SCHEDULED_TASK_RUN", "Task running") + // save the background JSON file + val timeStamp = Date().time / 1000 + val timeStampStr = timeStamp.toString() + val jsonBackground = "{\"batches\": \"0\", \"message\": \"Starting OK.\", \"date\": \"$timeStampStr\"}" + rpcModule.saveBackgroundFile(jsonBackground) + Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") + // checking if the wallet file exists val exists: Boolean = walletExists() @@ -60,7 +67,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // save the background JSON file val timeStamp = Date().time / 1000 val timeStampStr = timeStamp.toString() - val jsonBackground = "{\"batches\": \"0\", \"date\": \"$timeStampStr\"}" + val jsonBackground = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStr\"}" rpcModule.saveBackgroundFile(jsonBackground) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") From 67e8f10687cd20259ac050cd635ca659786891aa Mon Sep 17 00:00:00 2001 From: JC Date: Tue, 20 Feb 2024 15:26:34 -0700 Subject: [PATCH 19/41] fix: little fix --- .../main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index a3686b08d..b8913ca55 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -65,10 +65,10 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W Log.i("SCHEDULED_TASK_RUN", "wallet file SAVED") // save the background JSON file - val timeStamp = Date().time / 1000 - val timeStampStr = timeStamp.toString() - val jsonBackground = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStr\"}" - rpcModule.saveBackgroundFile(jsonBackground) + val timeStamp2 = Date().time / 1000 + val timeStampStr2 = timeStamp2.toString() + val jsonBackground2 = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStr2\"}" + rpcModule.saveBackgroundFile(jsonBackground2) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.success() From 96cc378d1edc6de3399dddde0b323e382668d09a Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 22 Feb 2024 08:45:27 -0700 Subject: [PATCH 20/41] fix: reagruping code for clarity sake --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 170 ++++++++++++++---- .../java/org/ZingoLabs/Zingo/MainActivity.kt | 91 +--------- 2 files changed, 139 insertions(+), 122 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index b8913ca55..b09d28e38 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -1,18 +1,45 @@ package org.ZingoLabs.Zingo import android.content.Context +import android.os.Build import androidx.work.Worker import androidx.work.WorkerParameters import android.util.Log +import androidx.annotation.RequiresApi +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.NetworkType +import androidx.work.PeriodicWorkRequest +import androidx.work.WorkManager import java.io.File import java.util.* import org.json.JSONObject import java.nio.charset.StandardCharsets import com.facebook.react.bridge.ReactApplicationContext +import kotlinx.datetime.Clock +import kotlinx.datetime.DateTimeUnit +import kotlinx.datetime.Instant +import kotlinx.datetime.TimeZone +import kotlinx.datetime.atTime +import kotlinx.datetime.toInstant +import kotlinx.datetime.toLocalDateTime +import kotlinx.datetime.until +import kotlin.random.Random +import kotlin.time.Duration +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes +import kotlin.time.DurationUnit +import kotlin.time.toDuration +import kotlin.time.toJavaDuration class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { + @RequiresApi(Build.VERSION_CODES.O) override fun doWork(): Result { + // first scheduling the same task for tomorrow + BSCompanion.scheduleBackgroundTask() + val reactContext = ReactApplicationContext(MainApplication.getAppContext()) val rpcModule = RPCModule(reactContext) @@ -40,7 +67,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } else { // this means the App is open, // stop syncing first, just in case. - BSCompanion.stopSyncingProcess() + stopSyncingProcess() } // interrupt sync to false, just in case it is true. @@ -92,6 +119,40 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } } + private fun stopSyncingProcess() { + val resp = RustFFI.execute("syncstatus", "") + Log.i("SCHEDULED_TASK_RUN", "status response $resp") + + var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) + var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + var inProgressStr: String = jsonResp.optString("in_progress") + var inProgress: Boolean = inProgressStr.toBoolean() + + Log.i("SCHEDULED_TASK_RUN", "in progress value $inProgress") + + while (inProgress) { + // interrupt + val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") + Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + + // blocking the thread for 0.5 seconds. + Thread.sleep(500) + + val resp3 = RustFFI.execute("syncstatus", "") + Log.i("SCHEDULED_TASK_RUN", "status response $resp3") + + data = resp.toByteArray(StandardCharsets.UTF_8) + jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) + inProgressStr = jsonResp.optString("in_progress") + inProgress = inProgressStr.toBoolean() + + Log.i("SCHEDULED_TASK_RUN", "in progress value $inProgress") + } + + Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED") + + } + private fun walletExists(): Boolean { // Check if a wallet already exists val file = File(MainApplication.getAppContext()?.filesDir, "wallet.dat") @@ -107,43 +168,84 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W class BSCompanion { companion object { - fun stopSyncingProcess() { - val resp = RustFFI.execute("syncstatus", "") - Log.i("SCHEDULED_TASK_RUN", "status response $resp") - - if (resp.lowercase().startsWith("error")) { - Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED - no lightwalletd likely") - return - } - - var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) - var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) - var inProgressStr: String = jsonResp.optString("in_progress") - var inProgress: Boolean = inProgressStr.toBoolean() - - Log.i("SCHEDULED_TASK_RUN", "in progress value $inProgress") - - while (inProgress) { - // interrupt - val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") - Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") - - // blocking the thread for 0.5 seconds. - Thread.sleep(500) - - val resp3 = RustFFI.execute("syncstatus", "") - Log.i("SCHEDULED_TASK_RUN", "status response $resp3") + private const val taskID = "Zingo_Processing_Task_ID" + private val SYNC_PERIOD = 24.hours + private val SYNC_DAY_SHIFT = 1.days // Move to tomorrow + private val SYNC_START_TIME_HOURS = 3.hours // Start around 3 a.m. at night + private val SYNC_START_TIME_MINUTES = 60.minutes // Randomize with minutes until 4 a.m. + @RequiresApi(Build.VERSION_CODES.O) + fun scheduleBackgroundTask() { + val reactContext = ReactApplicationContext(MainApplication.getAppContext()) + + val constraints = Constraints.Builder() + .setRequiresStorageNotLow(false) // less restricted + .setRequiredNetworkType(NetworkType.UNMETERED) + .setRequiresCharging(true) + .build() + + // PRODUCTION - next day between 3:00 and 4:00 am. + val targetTimeDiff = calculateTargetTimeDifference() + + Log.i("SCHEDULING_TASK", "calculated target time DIFF $targetTimeDiff") + + // DEVELOPMENT - after 5 minutes. + //val timeFiveMinutes: Long = 5 + + val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, SYNC_PERIOD.toJavaDuration()) + .setConstraints(constraints) + .setInitialDelay(targetTimeDiff.toJavaDuration()) + //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) + .build() + + Log.i("SCHEDULING_TASK", "Enqueuing the background task - Background") + WorkManager.getInstance(reactContext) + .enqueueUniquePeriodicWork( + taskID, + ExistingPeriodicWorkPolicy.REPLACE, + workRequest + ) + } - data = resp.toByteArray(StandardCharsets.UTF_8) - jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) - inProgressStr = jsonResp.optString("in_progress") - inProgress = inProgressStr.toBoolean() + private fun calculateTargetTimeDifference(): Duration { + val currentTimeZone: TimeZone = TimeZone.currentSystemDefault() + + val now: Instant = Clock.System.now() + + val targetTime = + now + .plus(SYNC_DAY_SHIFT) + .toLocalDateTime(currentTimeZone) + .date + .atTime( + hour = SYNC_START_TIME_HOURS.inWholeHours.toInt(), + // Even though the WorkManager will trigger the work approximately at the set time, it's + // better to randomize time in 3-4 a.m. This generates a number between 0 (inclusive) and 60 + // (exclusive) + minute = Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) + ) + + val targetTimeTime = targetTime.time + val targetTimeDate = targetTime.date + Log.i("SCHEDULING_TASK", "calculated target time $targetTimeTime and date $targetTimeDate") + + return now.until( + other = targetTime.toInstant(currentTimeZone), + unit = DateTimeUnit.MILLISECOND, + timeZone = currentTimeZone + ).toDuration(DurationUnit.MILLISECONDS) + } - Log.i("SCHEDULED_TASK_RUN", "in progress value $inProgress") - } + fun cancelExecutingTask() { + val reactContext = ReactApplicationContext(MainApplication.getAppContext()) - Log.i("SCHEDULED_TASK_RUN", "sync process STOPPED") + // run interrupt sync, just in case. + val resp = RustFFI.execute("interrupt_sync_after_batch", "true") + Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp") + Log.i("SCHEDULING_TASK", "Cancel background Task") + WorkManager.getInstance(reactContext) + .cancelUniqueWork(taskID) } + } } \ No newline at end of file diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 477c85a15..28236d44e 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -6,22 +6,7 @@ import android.util.Log import androidx.annotation.RequiresApi import androidx.work.* import com.facebook.react.ReactActivity -import kotlin.random.Random -import kotlin.time.Duration -import kotlin.time.Duration.Companion.days -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.minutes -import kotlin.time.DurationUnit -import kotlin.time.toDuration -import kotlin.time.toJavaDuration -import kotlinx.datetime.Clock -import kotlinx.datetime.DateTimeUnit -import kotlinx.datetime.Instant -import kotlinx.datetime.TimeZone -import kotlinx.datetime.atTime -import kotlinx.datetime.toInstant -import kotlinx.datetime.toLocalDateTime -import kotlinx.datetime.until + class MainActivity : ReactActivity() { /** @@ -29,11 +14,6 @@ class MainActivity : ReactActivity() { * rendering of the component. */ private val taskID = "Zingo_Processing_Task_ID" - private val SYNC_PERIOD = 24.hours - private val SYNC_DAY_SHIFT = 1.days // Move to tomorrow - private val SYNC_START_TIME_HOURS = 3.hours // Start around 3 a.m. at night - private val SYNC_START_TIME_MINUTES = 60.minutes // Randomize with minutes until 4 a.m. - override fun getMainComponentName(): String { return "Zingo!" } @@ -45,7 +25,7 @@ class MainActivity : ReactActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onPause() { Log.i("ON_PAUSE", "Pausing main activity - Background") - scheduleBackgroundTask() + BSCompanion.scheduleBackgroundTask() super.onPause() } @@ -53,73 +33,8 @@ class MainActivity : ReactActivity() { override fun onResume() { Log.i("ON_RESUME", "Resuming main activity - Foreground") // cancel the task if it is in execution now - cancelExecutingTask() + BSCompanion.cancelExecutingTask() super.onResume() } - private fun cancelExecutingTask() { - Log.i("SCHEDULING_TASK", "Cancel background Task") - WorkManager.getInstance(this) - .cancelUniqueWork(taskID) - } - - @RequiresApi(Build.VERSION_CODES.O) - private fun scheduleBackgroundTask() { - val constraints = Constraints.Builder() - .setRequiresStorageNotLow(false) // less restricted - .setRequiredNetworkType(NetworkType.UNMETERED) - .setRequiresCharging(true) - .build() - - // PRODUCTION - next day between 3:00 and 4:00 am. - val targetTimeDiff = calculateTargetTimeDifference() - - Log.i("SCHEDULING_TASK", "calculated target time DIFF $targetTimeDiff") - - // DEVELOPMENT - after 5 minutes. - //val timeFiveMinutes: Long = 5 - - val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, SYNC_PERIOD.toJavaDuration()) - .setConstraints(constraints) - .setInitialDelay(targetTimeDiff.toJavaDuration()) - //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) - .build() - - Log.i("SCHEDULING_TASK", "Enqueuing the background task - Background") - WorkManager.getInstance(this) - .enqueueUniquePeriodicWork( - taskID, - ExistingPeriodicWorkPolicy.REPLACE, - workRequest - ) - } - - private fun calculateTargetTimeDifference(): Duration { - val currentTimeZone: TimeZone = TimeZone.currentSystemDefault() - - val now: Instant = Clock.System.now() - - val targetTime = - now - .plus(SYNC_DAY_SHIFT) - .toLocalDateTime(currentTimeZone) - .date - .atTime( - hour = SYNC_START_TIME_HOURS.inWholeHours.toInt(), - // Even though the WorkManager will trigger the work approximately at the set time, it's - // better to randomize time in 3-4 a.m. This generates a number between 0 (inclusive) and 60 - // (exclusive) - minute = Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) - ) - - val targetTimeTime = targetTime.time - val targetTimeDate = targetTime.date - Log.i("SCHEDULING_TASK", "calculated target time $targetTimeTime and date $targetTimeDate") - - return now.until( - other = targetTime.toInstant(currentTimeZone), - unit = DateTimeUnit.MILLISECOND, - timeZone = currentTimeZone - ).toDuration(DurationUnit.MILLISECONDS) - } } \ No newline at end of file From 22b5f141d7be3e847bcaadd10b08cd145625ede1 Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 22 Feb 2024 12:18:46 -0700 Subject: [PATCH 21/41] fix: a couple of fixes --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 2 +- app/LoadedApp/LoadedApp.tsx | 4 +- app/rpc/RPC.ts | 45 ++++++++++++++++++- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index b09d28e38..32b59b783 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -141,7 +141,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val resp3 = RustFFI.execute("syncstatus", "") Log.i("SCHEDULED_TASK_RUN", "status response $resp3") - data = resp.toByteArray(StandardCharsets.UTF_8) + data = resp3.toByteArray(StandardCharsets.UTF_8) jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) inProgressStr = jsonResp.optString("in_progress") inProgress = inProgressStr.toBoolean() diff --git a/app/LoadedApp/LoadedApp.tsx b/app/LoadedApp/LoadedApp.tsx index 822e9a1b7..0b07a57ab 100644 --- a/app/LoadedApp/LoadedApp.tsx +++ b/app/LoadedApp/LoadedApp.tsx @@ -298,8 +298,8 @@ export class LoadedAppClass extends Component { if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { //console.log('App has come to the foreground!'); - // deactivate the interruption sync flag - await RPC.rpc_setInterruptSyncAfterBatch('false'); + // deactivate the interruption sync flag. No needed. + //await RPC.rpc_setInterruptSyncAfterBatch('false'); // reading background task info await this.fetchBackgroundSyncing(); // setting value for background task Android diff --git a/app/rpc/RPC.ts b/app/rpc/RPC.ts index f989c25e0..e9b12cbce 100644 --- a/app/rpc/RPC.ts +++ b/app/rpc/RPC.ts @@ -517,8 +517,17 @@ export default class RPC { return reducedDetailedTxns; } - // this is only for the first time when the App is booting. + // this is only for the first time when the App is booting, but + // there are more cases: + // - LoadedApp mounting component. + // - App go to Foreground. + // - Internet from Not Connected to Connected. + // - Cambio de Servidor. async configure(): Promise { + // First things first, I need to stop an existing sync process (if any) + // clean start. + await this.stopSyncProcess(); + // every 30 seconds the App try to Sync the new blocks. if (!this.refreshTimerID) { this.refreshTimerID = setInterval(() => { @@ -564,6 +573,40 @@ export default class RPC { }, 1000); } + sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); + + async stopSyncProcess(): Promise { + let returnStatus = await this.doSyncStatus(); + if (returnStatus.toLowerCase().startsWith('error')) { + return; + } + let ss = {} as RPCSyncStatusType; + try { + ss = await JSON.parse(returnStatus); + } catch (e) { + return; + } + + console.log('stop sync process. in progress', ss.in_progress); + + while (ss.in_progress) { + // interrupting sync process + await RPC.rpc_setInterruptSyncAfterBatch('true'); + + // sleep for half second + await this.sleep(500); + + returnStatus = await this.doSyncStatus(); + ss = await JSON.parse(returnStatus); + + console.log('stop sync process. in progress', ss.in_progress); + } + console.log('stop sync process. STOPPED'); + + // NOT interrupting sync process + await RPC.rpc_setInterruptSyncAfterBatch('false'); + } + async clearTimers(): Promise { if (this.refreshTimerID) { clearInterval(this.refreshTimerID); From 820c981f88295b520e199b36c55af1545a1ce619 Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 22 Feb 2024 12:27:17 -0700 Subject: [PATCH 22/41] fix: Android Test version 1.3.4 (138) --- android/app/build.gradle | 2 +- app/translations/en.json | 2 +- app/translations/es.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index b03633c8a..ce32ebe44 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 137 // Real + versionCode 138 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/app/translations/en.json b/app/translations/en.json index 1ee7c99ef..26bd9eaa4 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (137)", + "version": "zingo-1.3.4 (138)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index 1b238ee15..bebad714a 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (137)", + "version": "zingo-1.3.4 (138)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", From 4924b7524c5f7594ae91f261ec3b32dc5dc4f855 Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Thu, 22 Feb 2024 13:20:18 -0700 Subject: [PATCH 23/41] fix: IOS Test version 1.3.4 (138) --- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index 4b53f90ed..6ca6215e2 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 137; + CURRENT_PROJECT_VERSION = 138; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 137; + CURRENT_PROJECT_VERSION = 138; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; From c0dcc8f30febcbdf7ef9c7bec1922d95b86ff9da Mon Sep 17 00:00:00 2001 From: JC Date: Thu, 22 Feb 2024 15:38:32 -0700 Subject: [PATCH 24/41] fix: renaming vars for clarity --- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 44 +++++++++---------- .../java/org/ZingoLabs/Zingo/MainActivity.kt | 1 - 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 32b59b783..290ececc0 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -46,10 +46,10 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W Log.i("SCHEDULED_TASK_RUN", "Task running") // save the background JSON file - val timeStamp = Date().time / 1000 - val timeStampStr = timeStamp.toString() - val jsonBackground = "{\"batches\": \"0\", \"message\": \"Starting OK.\", \"date\": \"$timeStampStr\"}" - rpcModule.saveBackgroundFile(jsonBackground) + val timeStampStart = Date().time / 1000 + val timeStampStrStart = timeStampStart.toString() + val jsonBackgroundStart = "{\"batches\": \"0\", \"message\": \"Starting OK.\", \"date\": \"$timeStampStrStart\"}" + rpcModule.saveBackgroundFile(jsonBackgroundStart) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") // checking if the wallet file exists @@ -71,15 +71,15 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } // interrupt sync to false, just in case it is true. - val resp = RustFFI.execute("interrupt_sync_after_batch", "false") - Log.i("SCHEDULED_TASK_RUN", "Not interrupting sync: $resp") + val noInterrupting = RustFFI.execute("interrupt_sync_after_batch", "false") + Log.i("SCHEDULED_TASK_RUN", "Not interrupting sync: $noInterrupting") // the task is running here blocking this execution until this process finished: // 1. finished the syncing. Log.i("SCHEDULED_TASK_RUN", "sync BEGIN") - val resp2 = RustFFI.execute("sync", "") - Log.i("SCHEDULED_TASK_RUN", "sync END: $resp2") + val syncing = RustFFI.execute("sync", "") + Log.i("SCHEDULED_TASK_RUN", "sync END: $syncing") } else { Log.i("SCHEDULED_TASK_RUN", "No exists wallet file END") @@ -92,10 +92,10 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W Log.i("SCHEDULED_TASK_RUN", "wallet file SAVED") // save the background JSON file - val timeStamp2 = Date().time / 1000 - val timeStampStr2 = timeStamp2.toString() - val jsonBackground2 = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStr2\"}" - rpcModule.saveBackgroundFile(jsonBackground2) + val timeStampEnd = Date().time / 1000 + val timeStampStrEnd = timeStampEnd.toString() + val jsonBackgroundEnd = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStrEnd\"}" + rpcModule.saveBackgroundFile(jsonBackgroundEnd) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.success() @@ -120,10 +120,10 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } private fun stopSyncingProcess() { - val resp = RustFFI.execute("syncstatus", "") - Log.i("SCHEDULED_TASK_RUN", "status response $resp") + var status = RustFFI.execute("syncstatus", "") + Log.i("SCHEDULED_TASK_RUN", "status response $status") - var data: ByteArray = resp.toByteArray(StandardCharsets.UTF_8) + var data: ByteArray = status.toByteArray(StandardCharsets.UTF_8) var jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) var inProgressStr: String = jsonResp.optString("in_progress") var inProgress: Boolean = inProgressStr.toBoolean() @@ -132,16 +132,16 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W while (inProgress) { // interrupt - val resp2 = RustFFI.execute("interrupt_sync_after_batch", "true") - Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp2") + val interrupting = RustFFI.execute("interrupt_sync_after_batch", "true") + Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $interrupting") // blocking the thread for 0.5 seconds. Thread.sleep(500) - val resp3 = RustFFI.execute("syncstatus", "") - Log.i("SCHEDULED_TASK_RUN", "status response $resp3") + status = RustFFI.execute("syncstatus", "") + Log.i("SCHEDULED_TASK_RUN", "status response $status") - data = resp3.toByteArray(StandardCharsets.UTF_8) + data = status.toByteArray(StandardCharsets.UTF_8) jsonResp = JSONObject(String(data, StandardCharsets.UTF_8)) inProgressStr = jsonResp.optString("in_progress") inProgress = inProgressStr.toBoolean() @@ -239,8 +239,8 @@ class BSCompanion { val reactContext = ReactApplicationContext(MainApplication.getAppContext()) // run interrupt sync, just in case. - val resp = RustFFI.execute("interrupt_sync_after_batch", "true") - Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $resp") + val interrupting = RustFFI.execute("interrupt_sync_after_batch", "true") + Log.i("SCHEDULED_TASK_RUN", "Interrupting sync: $interrupting") Log.i("SCHEDULING_TASK", "Cancel background Task") WorkManager.getInstance(reactContext) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 28236d44e..7b3c2763f 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -13,7 +13,6 @@ class MainActivity : ReactActivity() { * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ - private val taskID = "Zingo_Processing_Task_ID" override fun getMainComponentName(): String { return "Zingo!" } From b447491c99d6fde8d9a05b60717ca1bed6228731 Mon Sep 17 00:00:00 2001 From: JC Date: Fri, 23 Feb 2024 07:14:35 -0700 Subject: [PATCH 25/41] fix: reverting code of isCharging check --- ios/ZingoMobile/AppDelegate.m | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index e6f72f75c..d39f131fa 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -34,7 +34,6 @@ @implementation AppDelegate static NSString* syncTask = @"Zingo_Processing_Task_ID"; static NSString* syncSchedulerTask = @"Zingo_Processing_Scheduler_Task_ID"; static BOOL isConnectedToWifi = false; -static BOOL isCharging = false; static BGProcessingTask *bgTask = nil; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions @@ -303,14 +302,7 @@ - (void)handleBackgroundTask { UIDeviceBatteryState currentState = [[UIDevice currentDevice] batteryState]; - if (currentState == UIDeviceBatteryStateCharging) { - // The battery is either charging, or connected to a charger. - isCharging = true; - } else { - isCharging = false; - } - - NSLog(@"BGTask isConnectedToWifi %@ isCharging %@", isConnectedToWifi ? @"true" : @"false", isCharging ? @"true" : @"false"); + NSLog(@"BGTask isConnectedToWifi %@", isConnectedToWifi ? @"true" : @"false"); [self registerTasks]; } @@ -366,21 +358,6 @@ - (void)startBackgroundTask:(NSString *)noValue { bgTask = nil; return; } - - if (!isCharging) { - // save info in background json - NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; - // NSTimeInterval is defined as double - NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; - NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No plug-in KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; - [rpcmodule saveBackgroundFile:jsonBackgroud]; - - NSLog(@"BGTask startBackgroundTask: not plug in to power"); - [bgTask setTaskCompletedWithSuccess:NO]; - bgTask = nil; - return; - } // Start the syncing NSLog(@"BGTask startBackgroundTask run sync task"); From 1e4caa29fdce75a6c001e66d665a140660433522 Mon Sep 17 00:00:00 2001 From: JC Date: Fri, 23 Feb 2024 08:12:36 -0700 Subject: [PATCH 26/41] fix: BS - adding message when there is not wallet file --- .../java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 6 ++++++ ios/ZingoMobile/AppDelegate.m | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 290ececc0..45d4ca03a 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -83,6 +83,12 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W } else { Log.i("SCHEDULED_TASK_RUN", "No exists wallet file END") + // save the background JSON file + val timeStampError = Date().time / 1000 + val timeStampStrError = timeStampError.toString() + val jsonBackgroundError = "{\"batches\": \"0\", \"message\": \"No wallet file KO.\", \"date\": \"$timeStampStrError\"}" + rpcModule.saveBackgroundFile(jsonBackgroundError) + Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.failure() } diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index d39f131fa..6ae77a442 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -215,6 +215,18 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { } else { NSLog(@"BGTask syncingProcessBackgroundTask - No exists wallet file END"); + // save info in background json + NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; + // NSTimeInterval is defined as double + NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; + NSString *timeStampStr = [timeStampObj stringValue]; + NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wallet file KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; + [rpcmodule saveBackgroundFile:jsonBackgroud]; + NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); + + [bgTask setTaskCompletedWithSuccess:NO]; + bgTask = nil; + return; } From 00aff974069bf0e42fdf43714965315f187d6c31 Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Fri, 23 Feb 2024 13:41:34 -0700 Subject: [PATCH 27/41] fix: IOS Test version 1.3.4 (139) & wifi and plug-in checking fixed --- android/app/build.gradle | 2 +- app/translations/en.json | 2 +- app/translations/es.json | 2 +- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 +- ios/ZingoMobile/AppDelegate.m | 175 ++++++++++++---------- 5 files changed, 99 insertions(+), 86 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index ce32ebe44..4e95d9cf4 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 138 // Real + versionCode 139 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/app/translations/en.json b/app/translations/en.json index 26bd9eaa4..a8a5ffb8f 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (138)", + "version": "zingo-1.3.4 (139)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index bebad714a..039c1f0d5 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (138)", + "version": "zingo-1.3.4 (139)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index 6ca6215e2..b96e9c5ee 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 138; + CURRENT_PROJECT_VERSION = 139; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 138; + CURRENT_PROJECT_VERSION = 139; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index 6ae77a442..150eea888 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -31,10 +31,9 @@ static void InitializeFlipper(UIApplication *application) { @implementation AppDelegate -static NSString* syncTask = @"Zingo_Processing_Task_ID"; -static NSString* syncSchedulerTask = @"Zingo_Processing_Scheduler_Task_ID"; -static BOOL isConnectedToWifi = false; -static BGProcessingTask *bgTask = nil; +NSString* syncTask = @"Zingo_Processing_Task_ID"; +NSString* syncSchedulerTask = @"Zingo_Processing_Scheduler_Task_ID"; +BGProcessingTask *bgTask = nil; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { @@ -56,8 +55,8 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [self.window makeKeyAndVisible]; if (@available(iOS 13.0, *)) { - NSLog(@"BGTask handleBackgroundTask"); - [self handleBackgroundTask]; + NSLog(@"BGTask registerTasks"); + [self registerTasks]; } return YES; @@ -133,36 +132,36 @@ -(void)stopSyncingProcess:(NSString *)noValue { @autoreleasepool { NSLog(@"BGTask stopSyncingProcess"); - char *resp = execute("syncstatus", ""); - NSString* respStr = [NSString stringWithUTF8String:resp]; - rust_free(resp); - NSLog(@"BGTask stopSyncingProcess - status response %@", respStr); + char *status = execute("syncstatus", ""); + NSString* statusStr = [NSString stringWithUTF8String:status]; + rust_free(status); + NSLog(@"BGTask stopSyncingProcess - status response %@", statusStr); - if ([respStr hasPrefix:@"Error"]) { + if ([statusStr hasPrefix:@"Error"]) { NSLog(@"BGTask stopSyncingProcess - no lightwalled likely"); return; } - NSData *data = [respStr dataUsingEncoding:NSUTF8StringEncoding]; + NSData *data = [statusStr dataUsingEncoding:NSUTF8StringEncoding]; id jsonResp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *inProgressStr = [jsonResp valueForKey:@"in_progress"]; BOOL inProgress = [inProgressStr boolValue]; while(inProgress) { - char *resp2 = execute("interrupt_sync_after_batch", "true"); - NSString* respStr2 = [NSString stringWithUTF8String:resp2]; - NSLog(@"BGTask stopSyncingProcess - interrupt syncing %@", respStr2); + char *interrupt = execute("interrupt_sync_after_batch", "true"); + NSString* interruptStr = [NSString stringWithUTF8String:interrupt]; + NSLog(@"BGTask stopSyncingProcess - interrupt syncing %@", interruptStr); [NSThread sleepForTimeInterval: 0.5]; - char *resp = execute("syncstatus", ""); - NSString* respStr = [NSString stringWithUTF8String:resp]; - rust_free(resp); - NSLog(@"BGTask stopSyncingProcess - status response %@", respStr); + status = execute("syncstatus", ""); + statusStr = [NSString stringWithUTF8String:status]; + rust_free(status); + NSLog(@"BGTask stopSyncingProcess - status response %@", statusStr); - NSData *data = [respStr dataUsingEncoding:NSUTF8StringEncoding]; - id jsonResp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; - NSString *inProgressStr = [jsonResp valueForKey:@"in_progress"]; + data = [statusStr dataUsingEncoding:NSUTF8StringEncoding]; + jsonResp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + inProgressStr = [jsonResp valueForKey:@"in_progress"]; inProgress = [inProgressStr boolValue]; } @@ -176,16 +175,27 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { //do things with task @autoreleasepool { + RPCModule *rpcmodule = [RPCModule new]; + + // save info in background json + NSTimeInterval timeStampStart = [[NSDate date] timeIntervalSince1970]; + // NSTimeInterval is defined as double + NSNumber *timeStampObjStart = [NSNumber numberWithDouble: timeStampStart]; + NSString *timeStampStrStart = [timeStampObjStart stringValue]; + NSString *jsonBackgroudStart = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Starting OK.", @"\", \"date\": \"", timeStampStrStart, @"\"}"]; + [rpcmodule saveBackgroundFile:jsonBackgroudStart]; + NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); + NSLog(@"BGTask syncingProcessBackgroundTask"); BOOL exists = [self wallet__exists]; if (exists) { // check the Server, because the task can run without the App. - char *bal = execute("balance", ""); - NSString* balStr = [NSString stringWithUTF8String:bal]; - NSLog(@"BGTask syncingProcessBackgroundTask - testing if server is active %@", balStr); - rust_free(bal); - if ([balStr hasPrefix:@"Error"]) { + char *balance = execute("balance", ""); + NSString* balanceStr = [NSString stringWithUTF8String:balance]; + NSLog(@"BGTask syncingProcessBackgroundTask - testing if server is active %@", balanceStr); + rust_free(balance); + if ([balanceStr hasPrefix:@"Error"]) { // this means this task is running with the App closed [self loadWalletFile:nil]; } else { @@ -195,10 +205,10 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { } // we need to sync without interruption, I run this just in case - char *resp = execute("interrupt_sync_after_batch", "false"); - NSString* respStr = [NSString stringWithUTF8String:resp]; - NSLog(@"BGTask syncingProcessBackgroundTask - no interrupt syncing %@", respStr); - rust_free(resp); + char *noInterrupt = execute("interrupt_sync_after_batch", "false"); + NSString* noInterruptStr = [NSString stringWithUTF8String:noInterrupt]; + NSLog(@"BGTask syncingProcessBackgroundTask - no interrupt syncing %@", noInterruptStr); + rust_free(noInterrupt); // the task is running here blocking this execution until this process finished: // 1. finished the syncing. @@ -206,22 +216,22 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { NSLog(@"BGTask syncingProcessBackgroundTask - sync BEGIN"); - char *resp2 = execute("sync", ""); - NSString* respStr2 = [NSString stringWithUTF8String:resp2]; - rust_free(resp2); + char *syncing = execute("sync", ""); + NSString* syncingStr = [NSString stringWithUTF8String:syncing]; + rust_free(syncing); - NSLog(@"BGTask syncingProcessBackgroundTask - sync END %@", respStr2); + NSLog(@"BGTask syncingProcessBackgroundTask - sync END %@", syncingStr); } else { NSLog(@"BGTask syncingProcessBackgroundTask - No exists wallet file END"); // save info in background json - NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; + NSTimeInterval timeStampError = [[NSDate date] timeIntervalSince1970]; // NSTimeInterval is defined as double - NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; - NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wallet file KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; - [rpcmodule saveBackgroundFile:jsonBackgroud]; + NSNumber *timeStampObjError = [NSNumber numberWithDouble: timeStampError]; + NSString *timeStampStrError = [timeStampObjError stringValue]; + NSString *jsonBackgroudError = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wallet file KO.", @"\", \"date\": \"", timeStampStrError, @"\"}"]; + [rpcmodule saveBackgroundFile:jsonBackgroudError]; NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); [bgTask setTaskCompletedWithSuccess:NO]; @@ -236,17 +246,16 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { // I'm gessing NO. // save the wallet - RPCModule *rpcmodule = [RPCModule new]; [rpcmodule saveWalletInternal]; NSLog(@"BGTask syncingProcessBackgroundTask - Save Wallet"); // save info in background json - NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; + NSTimeInterval timeStampEnd = [[NSDate date] timeIntervalSince1970]; // NSTimeInterval is defined as double - NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; - NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Finished OK.", @"\", \"date\": \"", timeStampStr, @"\"}"]; - [rpcmodule saveBackgroundFile:jsonBackgroud]; + NSNumber *timeStampObjEnd = [NSNumber numberWithDouble: timeStampEnd]; + NSString *timeStampStrEnd = [timeStampObjEnd stringValue]; + NSString *jsonBackgroudEnd = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Finished OK.", @"\", \"date\": \"", timeStampStrEnd, @"\"}"]; + [rpcmodule saveBackgroundFile:jsonBackgroudEnd]; NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); [bgTask setTaskCompletedWithSuccess:YES]; @@ -300,25 +309,6 @@ -(BOOL)wallet__exists { // NEW BACKGROUND SCHEDULING TASKS -- (void)handleBackgroundTask { - // We require the background task to run when connected to the power and wifi - Reachability *reachability = [Reachability reachabilityForInternetConnection]; - NetworkStatus networkStatus = [reachability currentReachabilityStatus]; - - if (networkStatus == ReachableViaWiFi) { - // the device have Wifi. - isConnectedToWifi = true; - } else { - isConnectedToWifi = false; - } - - UIDeviceBatteryState currentState = [[UIDevice currentDevice] batteryState]; - - NSLog(@"BGTask isConnectedToWifi %@", isConnectedToWifi ? @"true" : @"false"); - - [self registerTasks]; -} - - (void)registerTasks { BOOL bcgSyncTaskResult; bcgSyncTaskResult = [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:syncTask usingQueue:dispatch_get_main_queue() @@ -355,20 +345,43 @@ - (void)startBackgroundTask:(NSString *)noValue { // Schedule tasks for the next time [self scheduleBackgroundTask]; [self scheduleSchedulerBackgroundTask]; + + // We require the background task to run when connected to the power and wifi + Reachability *reachability = [Reachability reachabilityForInternetConnection]; + NetworkStatus networkStatus = [reachability currentReachabilityStatus]; - if (!isConnectedToWifi) { - // save info in background json - NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; - // NSTimeInterval is defined as double - NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; - NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wifi KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; - [rpcmodule saveBackgroundFile:jsonBackgroud]; - - NSLog(@"BGTask startBackgroundTask: not connected to the wifi"); - [bgTask setTaskCompletedWithSuccess:NO]; - bgTask = nil; - return; + if (networkStatus != ReachableViaWiFi) { + // the device have NOT Wifi. + // save info in background json + NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; + // NSTimeInterval is defined as double + NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; + NSString *timeStampStr = [timeStampObj stringValue]; + NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wifi KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; + [rpcmodule saveBackgroundFile:jsonBackgroud]; + + NSLog(@"BGTask startBackgroundTask: not connected to the wifi"); + [bgTask setTaskCompletedWithSuccess:NO]; + bgTask = nil; + return; + } + + UIDeviceBatteryState currentState = [[UIDevice currentDevice] batteryState]; + + if (currentState != UIDeviceBatteryStateCharging) { + // The battery is NOT either charging, or connected to a charger. + // save info in background json + NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; + // NSTimeInterval is defined as double + NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; + NSString *timeStampStr = [timeStampObj stringValue]; + NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No plug-in KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; + [rpcmodule saveBackgroundFile:jsonBackgroud]; + + NSLog(@"BGTask startBackgroundTask: not plup-in to power"); + [bgTask setTaskCompletedWithSuccess:NO]; + bgTask = nil; + return; } // Start the syncing @@ -382,9 +395,9 @@ - (void)startBackgroundTask:(NSString *)noValue { NSLog(@"BGTask startBackgroundTask - expirationHandler called"); // interrupting the sync process, I can't wait to see if the process is over // because I have no time enough to run all I need in this task. - char *resp2 = execute("interrupt_sync_after_batch", "true"); - NSString* respStr2 = [NSString stringWithUTF8String:resp2]; - NSLog(@"BGTask startBackgroundTask - expirationHandler interrupt syncing %@", respStr2); + char *interrupt = execute("interrupt_sync_after_batch", "true"); + NSString* interruptStr = [NSString stringWithUTF8String:interrupt]; + NSLog(@"BGTask startBackgroundTask - expirationHandler interrupt syncing %@", interruptStr); // save the wallet RPCModule *rpcmodule = [RPCModule new]; From 4582788c966df9d6c9521173469f68eb8abee04f Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Sat, 24 Feb 2024 07:45:05 -0700 Subject: [PATCH 28/41] fix: IOS & Android Test version 1.3.4 (140) --- android/app/build.gradle | 2 +- app/translations/en.json | 2 +- app/translations/es.json | 2 +- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 ++-- ios/ZingoMobile/AppDelegate.m | 18 ------------------ 5 files changed, 5 insertions(+), 23 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 4e95d9cf4..386baa231 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 139 // Real + versionCode 140 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/app/translations/en.json b/app/translations/en.json index a8a5ffb8f..845b49a2d 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (139)", + "version": "zingo-1.3.4 (140)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index 039c1f0d5..760b744a7 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (139)", + "version": "zingo-1.3.4 (140)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index b96e9c5ee..bdf2ada7a 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 139; + CURRENT_PROJECT_VERSION = 140; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 139; + CURRENT_PROJECT_VERSION = 140; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index 150eea888..9ae60a9c8 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -365,24 +365,6 @@ - (void)startBackgroundTask:(NSString *)noValue { bgTask = nil; return; } - - UIDeviceBatteryState currentState = [[UIDevice currentDevice] batteryState]; - - if (currentState != UIDeviceBatteryStateCharging) { - // The battery is NOT either charging, or connected to a charger. - // save info in background json - NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; - // NSTimeInterval is defined as double - NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; - NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No plug-in KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; - [rpcmodule saveBackgroundFile:jsonBackgroud]; - - NSLog(@"BGTask startBackgroundTask: not plup-in to power"); - [bgTask setTaskCompletedWithSuccess:NO]; - bgTask = nil; - return; - } // Start the syncing NSLog(@"BGTask startBackgroundTask run sync task"); From e148744d7a61420a0d5a1d5f68ee35d34d59c6f9 Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Sat, 24 Feb 2024 08:03:57 -0700 Subject: [PATCH 29/41] fix: IOS & Android Test version 1.3.4 (141) & BS Task not need to be plug-in --- android/app/build.gradle | 2 +- app/translations/en.json | 2 +- app/translations/es.json | 2 +- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 ++-- ios/ZingoMobile/AppDelegate.m | 3 ++- 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 386baa231..f85b998ee 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 140 // Real + versionCode 141 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/app/translations/en.json b/app/translations/en.json index 845b49a2d..a3582f3b3 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (140)", + "version": "zingo-1.3.4 (141)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index 760b744a7..bf130d491 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (140)", + "version": "zingo-1.3.4 (141)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index bdf2ada7a..efd4f53ba 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 140; + CURRENT_PROJECT_VERSION = 141; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 140; + CURRENT_PROJECT_VERSION = 141; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index 9ae60a9c8..435da65d1 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -426,7 +426,8 @@ - (void)scheduleBackgroundTask { request.earliestBeginDate = earlyMorning; //request.earliestBeginDate = twoMinutesLater; - request.requiresExternalPower = YES; + // zancas requeriment, not plug-in. + request.requiresExternalPower = NO; request.requiresNetworkConnectivity = YES; NSError *error = nil; From 18f39997b0e902c25b41a5f5d48bb22100253b15 Mon Sep 17 00:00:00 2001 From: JC Date: Sat, 24 Feb 2024 09:59:11 -0700 Subject: [PATCH 30/41] fix: IOS & Android Test version 1.3.4 (141) & BS Task not need to be plug-in --- .../java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 3 +-- app/LoadedApp/LoadedApp.tsx | 12 ++++-------- app/LoadingApp/LoadingApp.tsx | 10 +++------- 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 45d4ca03a..ba28cd605 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -183,10 +183,9 @@ class BSCompanion { fun scheduleBackgroundTask() { val reactContext = ReactApplicationContext(MainApplication.getAppContext()) + // zancas requeriment, not plug-in val constraints = Constraints.Builder() - .setRequiresStorageNotLow(false) // less restricted .setRequiredNetworkType(NetworkType.UNMETERED) - .setRequiresCharging(true) .build() // PRODUCTION - next day between 3:00 and 4:00 am. diff --git a/app/LoadedApp/LoadedApp.tsx b/app/LoadedApp/LoadedApp.tsx index 0b07a57ab..b6d578f60 100644 --- a/app/LoadedApp/LoadedApp.tsx +++ b/app/LoadedApp/LoadedApp.tsx @@ -9,7 +9,6 @@ import { EmitterSubscription, AppState, NativeEventSubscription, - Platform, Linking, SafeAreaView, } from 'react-native'; @@ -178,13 +177,10 @@ export default function LoadedApp(props: LoadedAppProps) { } // reading background task info - if (Platform.OS === 'ios') { - // this file only exists in IOS BS. - const backgroundJson = await BackgroundFileImpl.readBackground(); - //console.log('background', backgroundJson); - if (backgroundJson) { - setBackground(backgroundJson); - } + const backgroundJson = await BackgroundFileImpl.readBackground(); + //console.log('background', backgroundJson); + if (backgroundJson) { + setBackground(backgroundJson); } setLoading(false); })(); diff --git a/app/LoadingApp/LoadingApp.tsx b/app/LoadingApp/LoadingApp.tsx index 271abd854..d99bec4ee 100644 --- a/app/LoadingApp/LoadingApp.tsx +++ b/app/LoadingApp/LoadingApp.tsx @@ -12,7 +12,6 @@ import { EmitterSubscription, AppState, NativeEventSubscription, - Platform, TextInput, } from 'react-native'; import { useTheme } from '@react-navigation/native'; @@ -168,12 +167,9 @@ export default function LoadingApp(props: LoadingAppProps) { //await delay(5000); // reading background task info - if (Platform.OS === 'ios') { - // this file only exists in IOS BS. - const backgroundJson = await BackgroundFileImpl.readBackground(); - if (backgroundJson) { - setBackground(backgroundJson); - } + const backgroundJson = await BackgroundFileImpl.readBackground(); + if (backgroundJson) { + setBackground(backgroundJson); } setLoading(false); })(); From f3476ee88d23be3c57f36aedd5d6d3465ca5fdd2 Mon Sep 17 00:00:00 2001 From: JC Date: Sat, 24 Feb 2024 10:06:24 -0700 Subject: [PATCH 31/41] fix: Scheduling the BS Task for next day - Last setp of BS Task --- .../java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index ba28cd605..c80fac058 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -37,9 +37,6 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W @RequiresApi(Build.VERSION_CODES.O) override fun doWork(): Result { - // first scheduling the same task for tomorrow - BSCompanion.scheduleBackgroundTask() - val reactContext = ReactApplicationContext(MainApplication.getAppContext()) val rpcModule = RPCModule(reactContext) @@ -104,6 +101,9 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W rpcModule.saveBackgroundFile(jsonBackgroundEnd) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") + // the last thing... scheduling the same task for tomorrow + BSCompanion.scheduleBackgroundTask() + return Result.success() } @@ -218,15 +218,15 @@ class BSCompanion { val targetTime = now - .plus(SYNC_DAY_SHIFT) + //.plus(SYNC_DAY_SHIFT) .toLocalDateTime(currentTimeZone) .date .atTime( - hour = SYNC_START_TIME_HOURS.inWholeHours.toInt(), + hour = 10, //SYNC_START_TIME_HOURS.inWholeHours.toInt(), // Even though the WorkManager will trigger the work approximately at the set time, it's // better to randomize time in 3-4 a.m. This generates a number between 0 (inclusive) and 60 // (exclusive) - minute = Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) + minute = 10 //Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) ) val targetTimeTime = targetTime.time From dbed401e2bf13a684672745699083be6fff87452 Mon Sep 17 00:00:00 2001 From: JC Date: Sat, 24 Feb 2024 10:21:30 -0700 Subject: [PATCH 32/41] fix: Scheduling the BS Task for next day - Last step of BS Task - fix --- .../src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index c80fac058..06a60a71c 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -222,11 +222,11 @@ class BSCompanion { .toLocalDateTime(currentTimeZone) .date .atTime( - hour = 10, //SYNC_START_TIME_HOURS.inWholeHours.toInt(), + hour = SYNC_START_TIME_HOURS.inWholeHours.toInt(), // Even though the WorkManager will trigger the work approximately at the set time, it's // better to randomize time in 3-4 a.m. This generates a number between 0 (inclusive) and 60 // (exclusive) - minute = 10 //Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) + minute = Random.nextInt(0, SYNC_START_TIME_MINUTES.inWholeMinutes.toInt()) ) val targetTimeTime = targetTime.time From 8668c34e1776f552475d2b3d69253001d70cd48e Mon Sep 17 00:00:00 2001 From: JC Date: Sat, 24 Feb 2024 12:02:03 -0700 Subject: [PATCH 33/41] fix: Android Test version 1.3.4 (142) & BS little fix --- android/app/build.gradle | 2 +- .../src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 2 +- app/translations/en.json | 2 +- app/translations/es.json | 2 +- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index f85b998ee..28c3d6490 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 141 // Real + versionCode 142 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 06a60a71c..77f19a24b 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -218,7 +218,7 @@ class BSCompanion { val targetTime = now - //.plus(SYNC_DAY_SHIFT) + .plus(SYNC_DAY_SHIFT) .toLocalDateTime(currentTimeZone) .date .atTime( diff --git a/app/translations/en.json b/app/translations/en.json index a3582f3b3..f1b78a506 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (141)", + "version": "zingo-1.3.4 (142)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index bf130d491..39f6c5c64 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (141)", + "version": "zingo-1.3.4 (142)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index efd4f53ba..6254d6bdc 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 141; + CURRENT_PROJECT_VERSION = 142; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 141; + CURRENT_PROJECT_VERSION = 142; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; From a8d6ec8313fbdecad3d1e5ffe4d876fd98371e05 Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Sun, 25 Feb 2024 10:41:49 -0700 Subject: [PATCH 34/41] fix: IOS Test version 1.3.4 (143) --- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 +-- ios/ZingoMobile/AppDelegate.m | 42 +++-------------------- 2 files changed, 7 insertions(+), 39 deletions(-) diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index 6254d6bdc..59ac9db89 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 142; + CURRENT_PROJECT_VERSION = 143; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 142; + CURRENT_PROJECT_VERSION = 143; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index 435da65d1..ec1510e2d 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -230,7 +230,7 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { // NSTimeInterval is defined as double NSNumber *timeStampObjError = [NSNumber numberWithDouble: timeStampError]; NSString *timeStampStrError = [timeStampObjError stringValue]; - NSString *jsonBackgroudError = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wallet file KO.", @"\", \"date\": \"", timeStampStrError, @"\"}"]; + NSString *jsonBackgroudError = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No active wallet KO.", @"\", \"date\": \"", timeStampStrError, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudError]; NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); @@ -340,31 +340,10 @@ - (void)registerTasks { - (void)startBackgroundTask:(NSString *)noValue { NSLog(@"BGTask startBackgroundTask called"); - RPCModule *rpcmodule = [RPCModule new]; // Schedule tasks for the next time [self scheduleBackgroundTask]; [self scheduleSchedulerBackgroundTask]; - - // We require the background task to run when connected to the power and wifi - Reachability *reachability = [Reachability reachabilityForInternetConnection]; - NetworkStatus networkStatus = [reachability currentReachabilityStatus]; - - if (networkStatus != ReachableViaWiFi) { - // the device have NOT Wifi. - // save info in background json - NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; - // NSTimeInterval is defined as double - NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; - NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No wifi KO.", @"\", \"date\": \"", timeStampStr, @"\"}"]; - [rpcmodule saveBackgroundFile:jsonBackgroud]; - - NSLog(@"BGTask startBackgroundTask: not connected to the wifi"); - [bgTask setTaskCompletedWithSuccess:NO]; - bgTask = nil; - return; - } // Start the syncing NSLog(@"BGTask startBackgroundTask run sync task"); @@ -380,9 +359,10 @@ - (void)startBackgroundTask:(NSString *)noValue { char *interrupt = execute("interrupt_sync_after_batch", "true"); NSString* interruptStr = [NSString stringWithUTF8String:interrupt]; NSLog(@"BGTask startBackgroundTask - expirationHandler interrupt syncing %@", interruptStr); + + RPCModule *rpcmodule = [RPCModule new]; // save the wallet - RPCModule *rpcmodule = [RPCModule new]; [rpcmodule saveWalletInternal]; NSLog(@"BGTask startBackgroundTask - expirationHandler Save Wallet"); @@ -416,18 +396,12 @@ - (void)scheduleBackgroundTask { earlyMorningComponent.hour = 3; earlyMorningComponent.minute = arc4random_uniform(61); NSDate *earlyMorning = [[NSCalendar currentCalendar] dateByAddingComponents:earlyMorningComponent toDate:tomorrow options:0]; - - // DEVELOPMENT - //NSDate *now = [NSDate date]; - - //NSDate *twoMinutesLater = [now dateByAddingTimeInterval:120]; // 2 minutes = 120 seconds NSLog(@"BGTask scheduleBackgroundTask date calculated: %@", earlyMorning); request.earliestBeginDate = earlyMorning; - //request.earliestBeginDate = twoMinutesLater; - // zancas requeriment, not plug-in. - request.requiresExternalPower = NO; + // zancas requeriment, not plug-in, reverted. + request.requiresExternalPower = YES; request.requiresNetworkConnectivity = YES; NSError *error = nil; @@ -454,14 +428,8 @@ - (void)scheduleSchedulerBackgroundTask { afternoonComponent.hour = 14; afternoonComponent.minute = arc4random_uniform(61); NSDate *afternoon = [[NSCalendar currentCalendar] dateByAddingComponents:afternoonComponent toDate:tomorrow options:0]; - - // DEVELOPMENT - //NSDate *now = [NSDate date]; - - //NSDate *fiveMinutesLater = [now dateByAddingTimeInterval:300]; // 5 minutes = 300 seconds request.earliestBeginDate = afternoon; - //request.earliestBeginDate = fiveMinutesLater; request.requiresExternalPower = NO; request.requiresNetworkConnectivity = NO; From 160ab6600bba2cfd5881bdb794f57ee07d5691e6 Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Sun, 25 Feb 2024 10:45:38 -0700 Subject: [PATCH 35/41] fix: IOS Test version 1.3.4 (144) --- app/translations/en.json | 2 +- app/translations/es.json | 2 +- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/translations/en.json b/app/translations/en.json index f1b78a506..3ff26d870 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (142)", + "version": "zingo-1.3.4 (144)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index 39f6c5c64..7df4abe75 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (142)", + "version": "zingo-1.3.4 (144)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index 59ac9db89..b70c6f62e 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 143; + CURRENT_PROJECT_VERSION = 144; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 143; + CURRENT_PROJECT_VERSION = 144; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; From 93dca2c93b6774892d60fa4a4a7bd4593f34f5e9 Mon Sep 17 00:00:00 2001 From: JC Date: Sun, 25 Feb 2024 11:05:25 -0700 Subject: [PATCH 36/41] fix: Android Test version 1.3.4 (144) --- android/app/build.gradle | 2 +- .../main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 28c3d6490..c68b0e364 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 142 // Real + versionCode 144 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 77f19a24b..d68247332 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -83,7 +83,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // save the background JSON file val timeStampError = Date().time / 1000 val timeStampStrError = timeStampError.toString() - val jsonBackgroundError = "{\"batches\": \"0\", \"message\": \"No wallet file KO.\", \"date\": \"$timeStampStrError\"}" + val jsonBackgroundError = "{\"batches\": \"0\", \"message\": \"No active wallet KO.\", \"date\": \"$timeStampStrError\"}" rpcModule.saveBackgroundFile(jsonBackgroundError) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.failure() @@ -185,7 +185,9 @@ class BSCompanion { // zancas requeriment, not plug-in val constraints = Constraints.Builder() + .setRequiresStorageNotLow(false) // less restricted .setRequiredNetworkType(NetworkType.UNMETERED) + .setRequiresCharging(true) .build() // PRODUCTION - next day between 3:00 and 4:00 am. @@ -193,13 +195,9 @@ class BSCompanion { Log.i("SCHEDULING_TASK", "calculated target time DIFF $targetTimeDiff") - // DEVELOPMENT - after 5 minutes. - //val timeFiveMinutes: Long = 5 - val workRequest = PeriodicWorkRequest.Builder(BackgroundSyncWorker::class.java, SYNC_PERIOD.toJavaDuration()) .setConstraints(constraints) .setInitialDelay(targetTimeDiff.toJavaDuration()) - //.setInitialDelay(timeFiveMinutes, TimeUnit.MINUTES) .build() Log.i("SCHEDULING_TASK", "Enqueuing the background task - Background") From 0aedf3626110560cd0c4bf03bcd3b69ae4b9034b Mon Sep 17 00:00:00 2001 From: JC Date: Sun, 25 Feb 2024 14:41:07 -0700 Subject: [PATCH 37/41] fiX: Android Test version 1.3.4 (144) --- .../java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 6 +++--- .../src/main/java/org/ZingoLabs/Zingo/MainActivity.kt | 9 ++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index d68247332..7712c6aa6 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -101,9 +101,6 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W rpcModule.saveBackgroundFile(jsonBackgroundEnd) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") - // the last thing... scheduling the same task for tomorrow - BSCompanion.scheduleBackgroundTask() - return Result.success() } @@ -207,6 +204,9 @@ class BSCompanion { ExistingPeriodicWorkPolicy.REPLACE, workRequest ) + + Log.i("SCHEDULING_TASK", "Task info ${WorkManager.getInstance(reactContext).getWorkInfosForUniqueWork( + taskID).get()}") } private fun calculateTargetTimeDifference(): Duration { diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt index 7b3c2763f..0342e1aeb 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/MainActivity.kt @@ -13,6 +13,8 @@ class MainActivity : ReactActivity() { * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ + + private var isStarting = true; override fun getMainComponentName(): String { return "Zingo!" } @@ -32,7 +34,12 @@ class MainActivity : ReactActivity() { override fun onResume() { Log.i("ON_RESUME", "Resuming main activity - Foreground") // cancel the task if it is in execution now - BSCompanion.cancelExecutingTask() + if (isStarting) { + // this is the time the App is launching. + isStarting = false + } else { + BSCompanion.cancelExecutingTask() + } super.onResume() } From 3535d993fe44a6d99026220f053a4453edc69898 Mon Sep 17 00:00:00 2001 From: JC Date: Mon, 26 Feb 2024 09:04:37 -0700 Subject: [PATCH 38/41] fix: Android Test version 1.3.4 (145) & date end BS added --- __tests__/LoadedApp.snapshot.tsx | 5 ++- __tests__/LoadingApp.snapshot.tsx | 5 ++- android/app/build.gradle | 2 +- .../ZingoLabs/Zingo/BackgroundSyncWorker.kt | 8 ++-- app/AppState/types/BackgroundType.ts | 1 + app/LoadedApp/LoadedApp.tsx | 2 +- app/LoadingApp/LoadingApp.tsx | 2 +- app/context/contextAppLoaded.tsx | 2 + app/context/contextAppLoading.tsx | 2 + app/translations/en.json | 2 +- app/translations/es.json | 2 +- components/Background/BackgroundFileImpl.ts | 4 +- components/SyncReport/SyncReport.tsx | 41 ++++++++++--------- 13 files changed, 44 insertions(+), 34 deletions(-) diff --git a/__tests__/LoadedApp.snapshot.tsx b/__tests__/LoadedApp.snapshot.tsx index b9a2c929a..e2a8d93e2 100644 --- a/__tests__/LoadedApp.snapshot.tsx +++ b/__tests__/LoadedApp.snapshot.tsx @@ -13,7 +13,7 @@ import { ThemeType } from '../app/types'; // eslint-disable-next-line @typescript-eslint/no-unused-vars import { I18n } from 'i18n-js'; import { StackScreenProps } from '@react-navigation/stack'; -import { ServerType } from '../app/AppState'; +import { BackgroundType, ServerType } from '../app/AppState'; // Crea un mock para el constructor de I18n jest.mock('i18n-js', () => ({ @@ -121,10 +121,11 @@ describe('Component LoadedApp - test', () => { const sendAll = false; const privacy = false; const mode = 'basic'; - const background = { + const background: BackgroundType = { batches: 0, message: '', date: 0, + dateEnd: 0, }; const readOnly = false; const receive = render( diff --git a/__tests__/LoadingApp.snapshot.tsx b/__tests__/LoadingApp.snapshot.tsx index 55c628222..36a9ba9e0 100644 --- a/__tests__/LoadingApp.snapshot.tsx +++ b/__tests__/LoadingApp.snapshot.tsx @@ -13,7 +13,7 @@ import { ThemeType } from '../app/types'; // eslint-disable-next-line @typescript-eslint/no-unused-vars import { I18n } from 'i18n-js'; import { StackScreenProps } from '@react-navigation/stack'; -import { ServerType } from '../app/AppState'; +import { BackgroundType, ServerType } from '../app/AppState'; // Crea un mock para el constructor de I18n jest.mock('i18n-js', () => ({ @@ -121,10 +121,11 @@ describe('Component LoadingApp - test', () => { const sendAll = false; const privacy = false; const mode = 'basic'; - const background = { + const background: BackgroundType = { batches: 0, message: '', date: 0, + dateEnd: 0, }; const firstLaunchingMessage = false; const receive = render( diff --git a/android/app/build.gradle b/android/app/build.gradle index c68b0e364..986cf0229 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -144,7 +144,7 @@ android { //applicationId 'com.ZingoMobile' // @Test minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 144 // Real + versionCode 145 // Real //versionCode 117 // @Test versionName "zingo-1.3.4" // Real missingDimensionStrategy 'react-native-camera', 'general' diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 7712c6aa6..979505fef 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -45,7 +45,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // save the background JSON file val timeStampStart = Date().time / 1000 val timeStampStrStart = timeStampStart.toString() - val jsonBackgroundStart = "{\"batches\": \"0\", \"message\": \"Starting OK.\", \"date\": \"$timeStampStrStart\"}" + val jsonBackgroundStart = "{\"batches\": \"0\", \"message\": \"Starting OK.\", \"date\": \"$timeStampStrStart\", \"dateEnd\": \"0\"}" rpcModule.saveBackgroundFile(jsonBackgroundStart) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") @@ -83,7 +83,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // save the background JSON file val timeStampError = Date().time / 1000 val timeStampStrError = timeStampError.toString() - val jsonBackgroundError = "{\"batches\": \"0\", \"message\": \"No active wallet KO.\", \"date\": \"$timeStampStrError\"}" + val jsonBackgroundError = "{\"batches\": \"0\", \"message\": \"No active wallet KO.\", \"date\": \"$timeStampStrStart\", \"dateEnd\": \"$timeStampStrError\"}" rpcModule.saveBackgroundFile(jsonBackgroundError) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") return Result.failure() @@ -97,7 +97,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W // save the background JSON file val timeStampEnd = Date().time / 1000 val timeStampStrEnd = timeStampEnd.toString() - val jsonBackgroundEnd = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStrEnd\"}" + val jsonBackgroundEnd = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStrStart\", \"dateEnd\": \"$timeStampStrEnd\"}" rpcModule.saveBackgroundFile(jsonBackgroundEnd) Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") @@ -180,7 +180,7 @@ class BSCompanion { fun scheduleBackgroundTask() { val reactContext = ReactApplicationContext(MainApplication.getAppContext()) - // zancas requeriment, not plug-in + // zancas requeriment, not plug-in, reverted. val constraints = Constraints.Builder() .setRequiresStorageNotLow(false) // less restricted .setRequiredNetworkType(NetworkType.UNMETERED) diff --git a/app/AppState/types/BackgroundType.ts b/app/AppState/types/BackgroundType.ts index 901a27fe0..4ed0c3acf 100644 --- a/app/AppState/types/BackgroundType.ts +++ b/app/AppState/types/BackgroundType.ts @@ -2,5 +2,6 @@ export default interface BackgroundType { batches: number; message: string; date: number; + dateEnd: number; // eslint-disable-next-line semi } diff --git a/app/LoadedApp/LoadedApp.tsx b/app/LoadedApp/LoadedApp.tsx index b6d578f60..79d4dfae3 100644 --- a/app/LoadedApp/LoadedApp.tsx +++ b/app/LoadedApp/LoadedApp.tsx @@ -97,7 +97,7 @@ export default function LoadedApp(props: LoadedAppProps) { const [sendAll, setSendAll] = useState(false); const [privacy, setPrivacy] = useState(false); const [mode, setMode] = useState<'basic' | 'advanced'>('basic'); - const [background, setBackground] = useState({ batches: 0, message: '', date: 0 }); + const [background, setBackground] = useState({ batches: 0, message: '', date: 0, dateEnd: 0 }); const [loading, setLoading] = useState(true); const file = useMemo( () => ({ diff --git a/app/LoadingApp/LoadingApp.tsx b/app/LoadingApp/LoadingApp.tsx index d99bec4ee..4133d6b21 100644 --- a/app/LoadingApp/LoadingApp.tsx +++ b/app/LoadingApp/LoadingApp.tsx @@ -70,7 +70,7 @@ export default function LoadingApp(props: LoadingAppProps) { const [sendAll, setSendAll] = useState(false); const [privacy, setPrivacy] = useState(false); const [mode, setMode] = useState<'basic' | 'advanced'>('advanced'); // by default advanced - const [background, setBackground] = useState({ batches: 0, message: '', date: 0 }); + const [background, setBackground] = useState({ batches: 0, message: '', date: 0, dateEnd: 0 }); const [firstLaunchingMessage, setFirstLaunchingMessage] = useState(false); const [loading, setLoading] = useState(true); const file = useMemo( diff --git a/app/context/contextAppLoaded.tsx b/app/context/contextAppLoaded.tsx index 08d84dfda..0331e3e40 100644 --- a/app/context/contextAppLoaded.tsx +++ b/app/context/contextAppLoaded.tsx @@ -75,7 +75,9 @@ export const defaultAppStateLoaded: AppStateLoaded = { sendAll: false, background: { batches: 0, + message: '', date: 0, + dateEnd: 0, } as BackgroundType, translate: () => '', diff --git a/app/context/contextAppLoading.tsx b/app/context/contextAppLoading.tsx index cd6fcc9e6..f08648374 100644 --- a/app/context/contextAppLoading.tsx +++ b/app/context/contextAppLoading.tsx @@ -38,7 +38,9 @@ export const defaultAppStateLoading: AppStateLoading = { sendAll: false, background: { batches: 0, + message: '', date: 0, + dateEnd: 0, } as BackgroundType, translate: () => '', diff --git a/app/translations/en.json b/app/translations/en.json index 3ff26d870..4afda6409 100644 --- a/app/translations/en.json +++ b/app/translations/en.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (144)", + "version": "zingo-1.3.4 (145)", "loading": "loading...", "connectingserver": "Connecting to the server...", "wait": "Please wait...", diff --git a/app/translations/es.json b/app/translations/es.json index 7df4abe75..71a5c1b21 100644 --- a/app/translations/es.json +++ b/app/translations/es.json @@ -1,6 +1,6 @@ { "zingo": "Zingo!", - "version": "zingo-1.3.4 (144)", + "version": "zingo-1.3.4 (145)", "loading": "cargando...", "connectingserver": "Conectando con el servidor...", "wait": "Por favor espere...", diff --git a/components/Background/BackgroundFileImpl.ts b/components/Background/BackgroundFileImpl.ts index 4dcf38b1e..c6e10c952 100644 --- a/components/Background/BackgroundFileImpl.ts +++ b/components/Background/BackgroundFileImpl.ts @@ -10,7 +10,7 @@ export default class BackgroundFileImpl { // Write the server background static async reset() { const fileName = await this.getFileName(); - const newBackground: BackgroundType = { batches: 0, message: '', date: 0 }; + const newBackground: BackgroundType = { batches: 0, message: '', date: 0, dateEnd: 0 }; RNFS.writeFile(fileName, JSON.stringify(newBackground), 'utf8') .then(() => { @@ -34,7 +34,7 @@ export default class BackgroundFileImpl { } catch (err) { // File probably doesn't exist, so return nothing console.log('background json Error', err); - return { batches: 0, date: 0 } as BackgroundType; + return { batches: 0, message: '', date: 0, dateEnd: 0 } as BackgroundType; } } } diff --git a/components/SyncReport/SyncReport.tsx b/components/SyncReport/SyncReport.tsx index c2fa3ebf5..b1b50a93b 100644 --- a/components/SyncReport/SyncReport.tsx +++ b/components/SyncReport/SyncReport.tsx @@ -219,25 +219,28 @@ const SyncReport: React.FunctionComponent = ({ closeModal }) => /> )} - {Number(background.date) > 0 && showBackgroundLegend && ( - - - {!!background.message && {background.message}} - - )} + {(Number(background.date) > 0 || Number(background.dateEnd) > 0 || !!background.message) && + showBackgroundLegend && ( + + + {!!background.message && {background.message}} + + )} {maxBlocks && netInfo.isConnected ? ( <> From a76dc14146d3fbabced180bac4d502c8430024fa Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Mon, 26 Feb 2024 09:29:39 -0700 Subject: [PATCH 39/41] fix: IOS Test version 1.3.4 (145) & date end BS added --- ios/ZingoMobile.xcodeproj/project.pbxproj | 4 ++-- ios/ZingoMobile/AppDelegate.m | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/ios/ZingoMobile.xcodeproj/project.pbxproj b/ios/ZingoMobile.xcodeproj/project.pbxproj index b70c6f62e..494835773 100644 --- a/ios/ZingoMobile.xcodeproj/project.pbxproj +++ b/ios/ZingoMobile.xcodeproj/project.pbxproj @@ -533,7 +533,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 144; + CURRENT_PROJECT_VERSION = 145; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; @@ -573,7 +573,7 @@ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZingoMobile/ZingoMobile.entitlements; - CURRENT_PROJECT_VERSION = 144; + CURRENT_PROJECT_VERSION = 145; DEVELOPMENT_TEAM = 788KRST4S8; ENABLE_BITCODE = NO; EXCLUDED_ARCHS = ""; diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index ec1510e2d..0ef6a8031 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -34,6 +34,7 @@ @implementation AppDelegate NSString* syncTask = @"Zingo_Processing_Task_ID"; NSString* syncSchedulerTask = @"Zingo_Processing_Scheduler_Task_ID"; BGProcessingTask *bgTask = nil; +NSString* timeStampStrStart = nil; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { @@ -181,8 +182,8 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { NSTimeInterval timeStampStart = [[NSDate date] timeIntervalSince1970]; // NSTimeInterval is defined as double NSNumber *timeStampObjStart = [NSNumber numberWithDouble: timeStampStart]; - NSString *timeStampStrStart = [timeStampObjStart stringValue]; - NSString *jsonBackgroudStart = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Starting OK.", @"\", \"date\": \"", timeStampStrStart, @"\"}"]; + timeStampStrStart = [timeStampObjStart stringValue]; + NSString *jsonBackgroudStart = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Starting OK.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", @"0", @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudStart]; NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); @@ -230,7 +231,7 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { // NSTimeInterval is defined as double NSNumber *timeStampObjError = [NSNumber numberWithDouble: timeStampError]; NSString *timeStampStrError = [timeStampObjError stringValue]; - NSString *jsonBackgroudError = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No active wallet KO.", @"\", \"date\": \"", timeStampStrError, @"\"}"]; + NSString *jsonBackgroudError = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No active wallet KO.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", timeStampStrError, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudError]; NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); @@ -254,7 +255,7 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { // NSTimeInterval is defined as double NSNumber *timeStampObjEnd = [NSNumber numberWithDouble: timeStampEnd]; NSString *timeStampStrEnd = [timeStampObjEnd stringValue]; - NSString *jsonBackgroudEnd = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Finished OK.", @"\", \"date\": \"", timeStampStrEnd, @"\"}"]; + NSString *jsonBackgroudEnd = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Finished OK.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", timeStampStrEnd, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudEnd]; NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); @@ -371,7 +372,7 @@ - (void)startBackgroundTask:(NSString *)noValue { // NSTimeInterval is defined as double NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp]; NSString *timeStampStr = [timeStampObj stringValue]; - NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Expiration fired. Finished OK.", @"\", \"date\": \"", timeStampStr, @"\"}"]; + NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Expiration fired. Finished OK.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", timeStampStr, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroud]; NSLog(@"BGTask startBackgroundTask - expirationHandler Save background JSON"); From 792d44c5c9eb68fe1ad477ce4142ef740a1d453a Mon Sep 17 00:00:00 2001 From: JC Date: Mon, 26 Feb 2024 10:16:52 -0700 Subject: [PATCH 40/41] fix: adding logging & a fix --- .../main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt | 6 +++--- components/SyncReport/SyncReport.tsx | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt index 979505fef..26caf9213 100644 --- a/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt +++ b/android/app/src/main/java/org/ZingoLabs/Zingo/BackgroundSyncWorker.kt @@ -47,7 +47,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val timeStampStrStart = timeStampStart.toString() val jsonBackgroundStart = "{\"batches\": \"0\", \"message\": \"Starting OK.\", \"date\": \"$timeStampStrStart\", \"dateEnd\": \"0\"}" rpcModule.saveBackgroundFile(jsonBackgroundStart) - Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") + Log.i("SCHEDULED_TASK_RUN", "background json file SAVED $jsonBackgroundStart") // checking if the wallet file exists val exists: Boolean = walletExists() @@ -85,7 +85,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val timeStampStrError = timeStampError.toString() val jsonBackgroundError = "{\"batches\": \"0\", \"message\": \"No active wallet KO.\", \"date\": \"$timeStampStrStart\", \"dateEnd\": \"$timeStampStrError\"}" rpcModule.saveBackgroundFile(jsonBackgroundError) - Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") + Log.i("SCHEDULED_TASK_RUN", "background json file SAVED $jsonBackgroundError") return Result.failure() } @@ -99,7 +99,7 @@ class BackgroundSyncWorker(context: Context, workerParams: WorkerParameters) : W val timeStampStrEnd = timeStampEnd.toString() val jsonBackgroundEnd = "{\"batches\": \"0\", \"message\": \"Finished OK.\", \"date\": \"$timeStampStrStart\", \"dateEnd\": \"$timeStampStrEnd\"}" rpcModule.saveBackgroundFile(jsonBackgroundEnd) - Log.i("SCHEDULED_TASK_RUN", "background json file SAVED") + Log.i("SCHEDULED_TASK_RUN", "background json file SAVED $jsonBackgroundEnd") return Result.success() } diff --git a/components/SyncReport/SyncReport.tsx b/components/SyncReport/SyncReport.tsx index b1b50a93b..423e7affb 100644 --- a/components/SyncReport/SyncReport.tsx +++ b/components/SyncReport/SyncReport.tsx @@ -234,8 +234,9 @@ const SyncReport: React.FunctionComponent = ({ closeModal }) => //background.batches.toString() + //translate('report.batches-date') + moment(Number(Number(background.date).toFixed(0)) * 1000).format('YYYY MMM D h:mm a') + - ' - ' + - moment(Number(Number(background.dateEnd).toFixed(0)) * 1000).format('YYYY MMM D h:mm a') + (Number(background.dateEnd) > 0 + ? ' - ' + moment(Number(Number(background.dateEnd).toFixed(0)) * 1000).format('YYYY MMM D h:mm a') + : '') } /> {!!background.message && {background.message}} From c8b82d55ec82e9687f46f3d83bdda560e5cfdf8c Mon Sep 17 00:00:00 2001 From: Juan Carlos Carmona Calvo Date: Mon, 26 Feb 2024 10:44:20 -0700 Subject: [PATCH 41/41] fix: IOS adding logging --- ios/ZingoMobile/AppDelegate.m | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ios/ZingoMobile/AppDelegate.m b/ios/ZingoMobile/AppDelegate.m index 0ef6a8031..023d4cba0 100644 --- a/ios/ZingoMobile/AppDelegate.m +++ b/ios/ZingoMobile/AppDelegate.m @@ -185,7 +185,7 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { timeStampStrStart = [timeStampObjStart stringValue]; NSString *jsonBackgroudStart = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Starting OK.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", @"0", @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudStart]; - NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); + NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON %@", jsonBackgroudStart); NSLog(@"BGTask syncingProcessBackgroundTask"); BOOL exists = [self wallet__exists]; @@ -233,7 +233,7 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { NSString *timeStampStrError = [timeStampObjError stringValue]; NSString *jsonBackgroudError = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"No active wallet KO.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", timeStampStrError, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudError]; - NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); + NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON %@", jsonBackgroudError); [bgTask setTaskCompletedWithSuccess:NO]; bgTask = nil; @@ -257,7 +257,7 @@ -(void)syncingProcessBackgroundTask:(NSString *)noValue { NSString *timeStampStrEnd = [timeStampObjEnd stringValue]; NSString *jsonBackgroudEnd = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Finished OK.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", timeStampStrEnd, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroudEnd]; - NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON"); + NSLog(@"BGTask syncingProcessBackgroundTask - Save background JSON %@", jsonBackgroudEnd); [bgTask setTaskCompletedWithSuccess:YES]; bgTask = nil; @@ -374,7 +374,7 @@ - (void)startBackgroundTask:(NSString *)noValue { NSString *timeStampStr = [timeStampObj stringValue]; NSString *jsonBackgroud = [NSString stringWithFormat: @"%@%@%@%@%@%@%@%@%@", @"{\"batches\": \"", @"0", @"\", \"message\": \"", @"Expiration fired. Finished OK.", @"\", \"date\": \"", timeStampStrStart, @"\", \"dateEnd\": \"", timeStampStr, @"\"}"]; [rpcmodule saveBackgroundFile:jsonBackgroud]; - NSLog(@"BGTask startBackgroundTask - expirationHandler Save background JSON"); + NSLog(@"BGTask startBackgroundTask - expirationHandler Save background JSON %@", jsonBackgroud); [bgTask setTaskCompletedWithSuccess:NO]; bgTask = nil;