Skip to content

Commit

Permalink
push fixeds
Browse files Browse the repository at this point in the history
  • Loading branch information
polstianka committed Oct 5, 2024
1 parent cf8f8c7 commit b93e962
Show file tree
Hide file tree
Showing 31 changed files with 324 additions and 220 deletions.
34 changes: 18 additions & 16 deletions apps/wallet/api/src/main/java/com/tonapps/wallet/api/API.kt
Original file line number Diff line number Diff line change
Expand Up @@ -495,16 +495,14 @@ class API(
clientId: String,
body: String
) {
try {
val mimeType = "text/plain".toMediaType()
val url = "${BRIDGE_URL}/message?client_id=$publicKeyHex&to=$clientId&ttl=300"
val response = withRetry {
tonAPIHttpClient.post(url, body.toRequestBody(mimeType))
} ?: throw Exception("Empty response")
if (!response.isSuccessful) {
throw Exception("Failed sending event[code=${response.code};body=${response.body?.string()}]")
}
} catch (e: Throwable) { }
val mimeType = "text/plain".toMediaType()
val url = "${BRIDGE_URL}/message?client_id=$publicKeyHex&to=$clientId&ttl=300"
val response = withRetry {
tonAPIHttpClient.post(url, body.toRequestBody(mimeType))
} ?: throw Exception("Null response")
if (!response.isSuccessful) {
throw Exception("Failed sending event[code=${response.code};body=${response.body?.string()}]")
}
}

fun estimateGaslessCost(
Expand Down Expand Up @@ -716,12 +714,16 @@ class API(
json.put("silent", silent)
val data = json.toString().replace("\\/", "/").trim()

return withRetry {
tonAPIHttpClient.postJSON(url, data, ArrayMap<String, String>().apply {
set("X-TonConnect-Auth", token)
set("Connection", "close")
}).isSuccessful
} ?: false
val headers = ArrayMap<String, String>().apply {
set("X-TonConnect-Auth", token)
set("Connection", "close")
}

val response = withRetry {
tonAPIHttpClient.postJSON(url, data, headers)
}

return response?.isSuccessful ?: false
}

fun pushTonconnectUnsubscribe(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,4 @@ class BackupRepository(
addBackup(walletId, source, date)
}
}

fun addBackupsAsync(
walletIds: List<String>,
source: BackupEntity.Source = BackupEntity.Source.LOCAL,
date: Long = System.currentTimeMillis()
) {
scope.launch(Dispatchers.IO) { addBackups(walletIds, source, date) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.tonapps.wallet.data.dapps

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.collection.ArrayMap
import androidx.core.net.toUri
import com.tonapps.blockchain.ton.extensions.toRawAddress
Expand Down
1 change: 1 addition & 0 deletions apps/wallet/instance/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ android {

dependencies {
implementation(Dependence.Koin.core)
implementation(Dependence.Koin.workmanager)
implementation(Dependence.KotlinX.datetime)
implementation(Dependence.j2objc)
implementation(Dependence.cbor)
Expand Down
10 changes: 10 additions & 0 deletions apps/wallet/instance/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_push_channel_id" />
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import com.tonapps.extensions.setLocales
import com.tonapps.icu.CurrencyFormatter
import com.tonapps.tonkeeper.koin.koinModel
import com.tonapps.tonkeeper.koin.viewModelWalletModule
import com.tonapps.tonkeeper.koin.workerModule
import com.tonapps.tonkeeperx.BuildConfig
import com.tonapps.wallet.api.apiModule
import com.tonapps.wallet.data.account.accountModule
Expand All @@ -39,6 +40,7 @@ import com.tonapps.wallet.data.settings.SettingsRepository
import com.tonapps.wallet.data.staking.stakingModule
import org.koin.core.component.KoinComponent
import org.koin.android.ext.android.inject
import org.koin.androidx.workmanager.koin.workManagerFactory
import java.util.concurrent.Executors

class App: Application(), CameraXConfig.Provider, KoinComponent {
Expand Down Expand Up @@ -72,7 +74,8 @@ class App: Application(), CameraXConfig.Provider, KoinComponent {
instance = this
startKoin {
androidContext(this@App)
modules(koinModel, dAppsModule, viewModelWalletModule, purchaseModule, batteryModule, stakingModule, passcodeModule, rnLegacyModule, backupModule, dataModule, browserModule, apiModule, accountModule, ratesModule, tokenModule, eventsModule, collectiblesModule)
modules(koinModel, workerModule, dAppsModule, viewModelWalletModule, purchaseModule, batteryModule, stakingModule, passcodeModule, rnLegacyModule, backupModule, dataModule, browserModule, apiModule, accountModule, ratesModule, tokenModule, eventsModule, collectiblesModule)
workManagerFactory()
}
setLocales(settingsRepository.localeList)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Environment(context: Context) {
resultCode == ConnectionResult.SUCCESS
}

val isGooglePlayBillingAvailable: Boolean by lazy {
val isGooglePlayAvailable: Boolean by lazy {
installerSource == AppInstall.Source.GOOGLE_PLAY && isGooglePlayServicesAvailable
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ sealed class DeepLinkRoute {
val domain = uri.hostOrNull ?: return Unknown(uri)
try {
return when (domain) {
"backup" -> Backups
"backup", "backups" -> Backups
"staking" -> Staking
"buy-ton" -> Purchase
"send" -> Send
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import android.util.Log
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.work.WorkManager
import com.tonapps.blockchain.ton.contract.WalletVersion
import com.tonapps.extensions.bestMessage
import com.tonapps.tonkeeper.manager.tonconnect.TonConnectManager
Expand All @@ -28,6 +29,9 @@ import com.tonapps.wallet.localization.Localization
import uikit.navigation.Navigation
import uikit.navigation.Navigation.Companion.navigation

val Context.workManager: WorkManager
get() = WorkManager.getInstance(this)

fun Context.safeExternalOpenUri(uri: Uri) {
if (TonConnectManager.isTonConnectDeepLink(uri)) {
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import com.tonapps.tonkeeper.ui.screen.staking.unstake.UnStakeViewModel
import com.tonapps.tonkeeper.ui.screen.staking.stake.StakingViewModel
import com.tonapps.tonkeeper.ui.screen.send.transaction.SendTransactionViewModel
import com.tonapps.tonkeeper.ui.screen.staking.withdraw.StakeWithdrawViewModel
import org.koin.androidx.viewmodel.dsl.viewModel

val viewModelWalletModule = module {
viewModelOf(::WalletViewModel)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.tonapps.tonkeeper.koin

import com.tonapps.tonkeeper.worker.DAppPushToggleWorker
import org.koin.androidx.workmanager.dsl.workerOf
import org.koin.dsl.module

val workerModule = module {
workerOf(::DAppPushToggleWorker)
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.tonapps.tonkeeper.manager.push

import android.content.Context
import android.util.Log
import com.tonapps.extensions.locale
import com.tonapps.wallet.api.API
import com.tonapps.wallet.data.account.AccountRepository
Expand All @@ -24,8 +25,14 @@ class PushManager(
private val dAppsRepository: DAppsRepository,
) {

enum class State {
Enable, Disable, Delete
enum class State(val code: Int) {
Enable(1), Disable(0), Delete(-1);

companion object {
fun of(code: Int): State {
return entries.firstOrNull { it.code == code } ?: Disable
}
}
}

fun newFirebaseToken() {
Expand All @@ -36,14 +43,6 @@ class PushManager(
}
}

fun walletAsync(wallet: WalletEntity, state: State) {
scope.launch { wallet(wallet, state) }
}

fun walletsAsync(wallets: List<WalletEntity>, state: State) {
scope.launch { wallets(wallets, state) }
}

suspend fun wallet(wallet: WalletEntity, state: State) = wallets(listOf(wallet), state)

suspend fun wallets(wallets: List<WalletEntity>, state: State): Boolean = withContext(Dispatchers.IO) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.tonapps.tonkeeper.manager.tonconnect
import android.content.Context
import android.net.Uri
import android.util.ArrayMap
import android.util.Log
import androidx.core.net.toUri
import com.tonapps.blockchain.ton.extensions.equalsAddress
import com.tonapps.blockchain.ton.proof.TONProof
Expand All @@ -22,6 +21,7 @@ import com.tonapps.tonkeeper.manager.tonconnect.bridge.model.BridgeError
import com.tonapps.tonkeeper.manager.tonconnect.bridge.model.BridgeMethod
import com.tonapps.tonkeeper.manager.tonconnect.exceptions.ManifestException
import com.tonapps.tonkeeper.ui.screen.tonconnect.TonConnectScreen
import com.tonapps.tonkeeper.worker.DAppPushToggleWorker
import com.tonapps.wallet.api.API
import com.tonapps.wallet.data.account.entities.WalletEntity
import com.tonapps.wallet.data.dapps.DAppsRepository
Expand Down Expand Up @@ -137,7 +137,7 @@ class TonConnectManager(
proof: TONProof.Result?,
pushEnabled: Boolean,
type: AppConnectEntity.Type
): AppConnectEntity {
): AppConnectEntity = withContext(Dispatchers.IO) {
val timestamp = proof?.timestamp ?: (System.currentTimeMillis() / 1000L)
val connection = AppConnectEntity(
accountId = wallet.accountId,
Expand All @@ -154,15 +154,7 @@ class TonConnectManager(
if (!dAppsRepository.newConnect(connection)) {
throw Exception("Failed to save connection")
}
setPushEnabled(wallet, appUrl, pushEnabled)
return connection
}

suspend fun setPushEnabled(wallet: WalletEntity, appUrl: Uri, enabled: Boolean) {
val connections = dAppsRepository.setPushEnabled(wallet.accountId, wallet.testnet, appUrl, enabled)
if (!pushManager.dAppPush(wallet, connections, enabled)) {
dAppsRepository.setPushEnabled(wallet.accountId, wallet.testnet, appUrl, !enabled)
}
connection
}

fun processDeeplink(
Expand Down Expand Up @@ -222,7 +214,7 @@ class TonConnectManager(
)
val bundle = activity.addForResult(screen)
val response = screen.contract.parseResult(bundle)
newConnect(
val connect = newConnect(
wallet = response.wallet,
keyPair = keyPair,
clientId = clientId,
Expand All @@ -231,6 +223,16 @@ class TonConnectManager(
pushEnabled = response.notifications,
type = if (tonConnect.jsInject) AppConnectEntity.Type.Internal else AppConnectEntity.Type.External
)

activity.runOnUiThread {
DAppPushToggleWorker.run(
context = activity,
wallet = response.wallet,
appUrl = app.url,
enable = response.notifications
)
}

JsonBuilder.connectEventSuccess(
wallet = response.wallet,
proof = response.proof,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.tonapps.tonkeeper.manager.tonconnect.bridge

import android.util.Log
import com.tonapps.blockchain.ton.proof.TONProof
import com.tonapps.extensions.base64
import com.tonapps.extensions.optStringCompat
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import com.tonapps.tonkeeper.extensions.showToast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
Expand All @@ -24,6 +25,7 @@ import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.observeOn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uikit.base.BaseFragment
import uikit.navigation.Navigation
import uikit.navigation.Navigation.Companion.navigation
Expand All @@ -49,10 +51,6 @@ abstract class BaseWalletVM(
val context: Context
get() = holder?.uiContext ?: getApplication()

private val uiHandler: Handler by lazy {
Handler(context.mainLooper)
}

private val navigation: Navigation?
get() = Navigation.from(context)

Expand All @@ -68,18 +66,6 @@ abstract class BaseWalletVM(
this.onEach { action(it) }.launch()
}

fun <T> Flow<T>.safeCollectFlow(action: suspend (T) -> Unit) {
this.flowOn(Dispatchers.IO).onEach { action(it) }.catch {
toast(it.bestMessage)
}.launch()
}

fun <T> Flow<T>.safeCollectFlowAtPost(action: (T) -> Unit) {
this.safeCollectFlow {
post { action(it) }
}
}

fun detachHolder() {
holderRef?.clear()
holderRef = null
Expand All @@ -103,33 +89,15 @@ abstract class BaseWalletVM(
}
}

fun post(action: () -> Unit) {
uiHandler.post(action)
}

fun postDelayed(delay: Long, runnable: Runnable) {
uiHandler.postDelayed(runnable, delay)
}

fun cancelPost(runnable: Runnable) {
uiHandler.removeCallbacks(runnable)
}

fun toast(@StringRes resId: Int) {
post {
context.showToast(resId)
}
suspend fun toast(@StringRes resId: Int) = withContext(Dispatchers.Main) {
context.showToast(resId)
}

fun toast(text: String) {
post {
context.showToast(text)
}
suspend fun toast(text: String) = withContext(Dispatchers.Main) {
context.showToast(text)
}

fun openScreen(screen: BaseFragment) {
post {
navigation?.add(screen)
}
suspend fun openScreen(screen: BaseFragment) = withContext(Dispatchers.Main) {
navigation?.add(screen)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import android.util.Log
import android.util.TypedValue
import android.view.KeyEvent
import android.view.View
import androidx.appcompat.R
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.findViewTreeLifecycleOwner
Expand All @@ -28,7 +29,7 @@ import uikit.extensions.setStartDrawable
class WordEditText @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyle: Int = R.attr.editTextStyle,
) : AppCompatEditText(context, attrs, defStyle) {

var doOnTextChanged: ((Editable) -> Unit)? = null
Expand Down
Loading

0 comments on commit b93e962

Please sign in to comment.