Search in sources :

Example 1 with ExchangeRateEntry

use of de.schildbach.wallet.exchangerate.ExchangeRateEntry in project bitcoin-wallet by bitcoin-wallet.

the class WalletBalanceFragment method updateView.

private void updateView() {
    final BlockchainState blockchainState = application.blockchainState.getValue();
    final Coin balance = viewModel.getBalance().getValue();
    final boolean showLocalBalance = getResources().getBoolean(R.bool.show_local_balance) && config.isEnableExchangeRates();
    final ExchangeRateEntry exchangeRate = viewModel.getExchangeRate().getValue();
    final boolean showProgress;
    if (blockchainState != null && blockchainState.bestChainDate != null) {
        final long blockchainLag = System.currentTimeMillis() - blockchainState.bestChainDate.getTime();
        final boolean blockchainUptodate = blockchainLag < BLOCKCHAIN_UPTODATE_THRESHOLD_MS;
        final boolean noImpediments = blockchainState.impediments.isEmpty();
        showProgress = !(blockchainUptodate || !blockchainState.replaying);
        final String downloading = getString(noImpediments ? R.string.blockchain_state_progress_downloading : R.string.blockchain_state_progress_stalled);
        if (blockchainLag < 2 * DateUtils.DAY_IN_MILLIS) {
            final long hours = blockchainLag / DateUtils.HOUR_IN_MILLIS;
            viewProgress.setText(getString(R.string.blockchain_state_progress_hours, downloading, hours));
        } else if (blockchainLag < 2 * DateUtils.WEEK_IN_MILLIS) {
            final long days = blockchainLag / DateUtils.DAY_IN_MILLIS;
            viewProgress.setText(getString(R.string.blockchain_state_progress_days, downloading, days));
        } else if (blockchainLag < 90 * DateUtils.DAY_IN_MILLIS) {
            final long weeks = blockchainLag / DateUtils.WEEK_IN_MILLIS;
            viewProgress.setText(getString(R.string.blockchain_state_progress_weeks, downloading, weeks));
        } else {
            final long months = blockchainLag / (30 * DateUtils.DAY_IN_MILLIS);
            viewProgress.setText(getString(R.string.blockchain_state_progress_months, downloading, months));
        }
    } else {
        showProgress = false;
    }
    if (!showProgress) {
        viewBalance.setVisibility(View.VISIBLE);
        if (!showLocalBalance)
            viewBalanceLocal.setVisibility(View.GONE);
        if (balance != null) {
            viewBalanceBtc.setVisibility(View.VISIBLE);
            viewBalanceBtc.setFormat(config.getFormat());
            viewBalanceBtc.setAmount(balance);
            if (showLocalBalance) {
                if (exchangeRate != null) {
                    final Fiat localValue = exchangeRate.exchangeRate().coinToFiat(balance);
                    viewBalanceLocal.setVisibility(View.VISIBLE);
                    viewBalanceLocal.setFormat(Constants.LOCAL_FORMAT.code(0, Constants.PREFIX_ALMOST_EQUAL_TO + exchangeRate.getCurrencyCode()));
                    viewBalanceLocal.setAmount(localValue);
                    viewBalanceLocal.setTextColor(activity.getColor(R.color.fg_less_significant));
                } else {
                    viewBalanceLocal.setVisibility(View.INVISIBLE);
                }
            }
        } else {
            viewBalanceBtc.setVisibility(View.INVISIBLE);
        }
        viewProgress.setVisibility(View.GONE);
    } else {
        viewProgress.setVisibility(View.VISIBLE);
        viewBalance.setVisibility(View.INVISIBLE);
    }
}
Also used : BlockchainState(de.schildbach.wallet.service.BlockchainState) Coin(org.bitcoinj.core.Coin) ExchangeRateEntry(de.schildbach.wallet.exchangerate.ExchangeRateEntry) Fiat(org.bitcoinj.utils.Fiat)

Example 2 with ExchangeRateEntry

use of de.schildbach.wallet.exchangerate.ExchangeRateEntry in project bitcoin-wallet by bitcoin-wallet.

the class BlockchainService method onCreate.

@Override
public void onCreate() {
    serviceUpTime = Stopwatch.createStarted();
    log.debug(".onCreate()");
    super.onCreate();
    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    log.info("acquiring {}", wakeLock);
    wakeLock.acquire();
    connectivityNotification.setColor(getColor(R.color.fg_network_significant));
    connectivityNotification.setContentTitle(getString(config.isTrustedPeersOnly() ? R.string.notification_connectivity_syncing_trusted_peer : R.string.notification_connectivity_syncing_message));
    connectivityNotification.setContentIntent(PendingIntent.getActivity(BlockchainService.this, 0, new Intent(BlockchainService.this, WalletActivity.class), 0));
    connectivityNotification.setWhen(System.currentTimeMillis());
    connectivityNotification.setOngoing(true);
    connectivityNotification.setPriority(NotificationCompat.PRIORITY_LOW);
    startForeground(0);
    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());
    addressBookDao = AddressBookDatabase.getDatabase(application).addressBookDao();
    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    config.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
    registerReceiver(deviceIdleModeReceiver, new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
    peerConnectivityListener = new PeerConnectivityListener();
    broadcastPeerState(0);
    final WalletBalanceLiveData walletBalance = new WalletBalanceLiveData(application);
    final SelectedExchangeRateLiveData exchangeRate = new SelectedExchangeRateLiveData(application);
    walletBalance.observe(this, balance -> {
        final ExchangeRateEntry rate = exchangeRate.getValue();
        if (balance != null)
            WalletBalanceWidgetProvider.updateWidgets(BlockchainService.this, balance, rate != null ? rate.exchangeRate() : null);
    });
    exchangeRate.observe(this, rate -> {
        final Coin balance = walletBalance.getValue();
        if (balance != null)
            WalletBalanceWidgetProvider.updateWidgets(BlockchainService.this, balance, rate != null ? rate.exchangeRate() : null);
    });
    wallet = new WalletLiveData(application);
    wallet.observe(this, new Observer<Wallet>() {

        @Override
        public void onChanged(final Wallet wallet) {
            BlockchainService.this.wallet.removeObserver(this);
            final boolean blockChainFileExists = blockChainFile.exists();
            if (!blockChainFileExists) {
                log.info("blockchain does not exist, resetting wallet");
                wallet.reset();
            }
            try {
                blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile, Constants.Files.BLOCKCHAIN_STORE_CAPACITY, true);
                // detect corruptions as early as possible
                blockStore.getChainHead();
                final long earliestKeyCreationTimeSecs = wallet.getEarliestKeyCreationTime();
                if (!blockChainFileExists && earliestKeyCreationTimeSecs > 0) {
                    try {
                        log.info("loading checkpoints for birthdate {} from '{}'", Utils.dateTimeFormat(earliestKeyCreationTimeSecs * 1000), Constants.Files.CHECKPOINTS_ASSET);
                        final Stopwatch watch = Stopwatch.createStarted();
                        final InputStream checkpointsInputStream = getAssets().open(Constants.Files.CHECKPOINTS_ASSET);
                        CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore, earliestKeyCreationTimeSecs);
                        watch.stop();
                        log.info("checkpoints loaded, took {}", watch);
                    } catch (final IOException x) {
                        log.error("problem reading checkpoints, continuing without", x);
                    }
                }
            } catch (final BlockStoreException x) {
                blockChainFile.delete();
                final String msg = "blockstore cannot be created";
                log.error(msg, x);
                throw new Error(msg, x);
            }
            try {
                blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
            } catch (final BlockStoreException x) {
                throw new Error("blockchain cannot be created", x);
            }
            observeLiveDatasThatAreDependentOnWalletAndBlockchain();
        }
    });
}
Also used : IntentFilter(android.content.IntentFilter) BlockStoreException(org.bitcoinj.store.BlockStoreException) BlockChain(org.bitcoinj.core.BlockChain) Wallet(org.bitcoinj.wallet.Wallet) InputStream(java.io.InputStream) SPVBlockStore(org.bitcoinj.store.SPVBlockStore) Stopwatch(com.google.common.base.Stopwatch) Handler(android.os.Handler) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) IOException(java.io.IOException) WalletLiveData(de.schildbach.wallet.data.WalletLiveData) ExchangeRateEntry(de.schildbach.wallet.exchangerate.ExchangeRateEntry) Coin(org.bitcoinj.core.Coin) HandlerThread(android.os.HandlerThread) SelectedExchangeRateLiveData(de.schildbach.wallet.data.SelectedExchangeRateLiveData) File(java.io.File) WalletBalanceLiveData(de.schildbach.wallet.data.WalletBalanceLiveData)

Example 3 with ExchangeRateEntry

use of de.schildbach.wallet.exchangerate.ExchangeRateEntry in project bitcoin-wallet by bitcoin-wallet.

the class WalletBalanceWidgetProvider method onUpdate.

@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
    final PendingResult result = goAsync();
    AsyncTask.execute(() -> {
        final WalletApplication application = (WalletApplication) context.getApplicationContext();
        final Coin balance = application.getWallet().getBalance(BalanceType.ESTIMATED);
        final Configuration config = application.getConfiguration();
        final ExchangeRatesRepository exchangeRatesRepository = ExchangeRatesRepository.get(application);
        final ExchangeRateEntry exchangeRate = config.isEnableExchangeRates() ? exchangeRatesRepository.exchangeRateDao().findByCurrencyCode(config.getExchangeCurrencyCode()) : null;
        updateWidgets(context, appWidgetManager, appWidgetIds, balance, exchangeRate != null ? exchangeRate.exchangeRate() : null);
        result.finish();
    });
}
Also used : Coin(org.bitcoinj.core.Coin) ExchangeRateEntry(de.schildbach.wallet.exchangerate.ExchangeRateEntry) ExchangeRatesRepository(de.schildbach.wallet.exchangerate.ExchangeRatesRepository)

Example 4 with ExchangeRateEntry

use of de.schildbach.wallet.exchangerate.ExchangeRateEntry in project bitcoin-wallet by bitcoin-wallet.

the class WalletBalanceWidgetProvider method onAppWidgetOptionsChanged.

@Override
public void onAppWidgetOptionsChanged(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId, final Bundle newOptions) {
    if (newOptions != null)
        log.info("app widget {} options changed: minWidth={}", appWidgetId, newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH));
    final PendingResult result = goAsync();
    AsyncTask.execute(() -> {
        final WalletApplication application = (WalletApplication) context.getApplicationContext();
        final Coin balance = application.getWallet().getBalance(BalanceType.ESTIMATED);
        final Configuration config = application.getConfiguration();
        final ExchangeRatesRepository exchangeRatesRepository = ExchangeRatesRepository.get(application);
        final ExchangeRateEntry exchangeRate = config.isEnableExchangeRates() ? exchangeRatesRepository.exchangeRateDao().findByCurrencyCode(config.getExchangeCurrencyCode()) : null;
        updateWidget(context, appWidgetManager, appWidgetId, newOptions, balance, exchangeRate != null ? exchangeRate.exchangeRate() : null);
        result.finish();
    });
}
Also used : Coin(org.bitcoinj.core.Coin) ExchangeRateEntry(de.schildbach.wallet.exchangerate.ExchangeRateEntry) ExchangeRatesRepository(de.schildbach.wallet.exchangerate.ExchangeRatesRepository)

Example 5 with ExchangeRateEntry

use of de.schildbach.wallet.exchangerate.ExchangeRateEntry in project bitcoin-wallet by bitcoin-wallet.

the class SelectedExchangeRateLiveData method onChange.

private void onChange() {
    AsyncTask.execute(() -> {
        if (config.isEnableExchangeRates()) {
            final String currencyCode = config.getExchangeCurrencyCode();
            final ExchangeRateEntry exchangeRate = dao.findByCurrencyCode(currencyCode);
            postValue(exchangeRate);
        } else {
            postValue(null);
        }
    });
}
Also used : ExchangeRateEntry(de.schildbach.wallet.exchangerate.ExchangeRateEntry)

Aggregations

ExchangeRateEntry (de.schildbach.wallet.exchangerate.ExchangeRateEntry)6 Coin (org.bitcoinj.core.Coin)4 ExchangeRatesRepository (de.schildbach.wallet.exchangerate.ExchangeRatesRepository)2 Fiat (org.bitcoinj.utils.Fiat)2 PendingIntent (android.app.PendingIntent)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 Handler (android.os.Handler)1 HandlerThread (android.os.HandlerThread)1 Stopwatch (com.google.common.base.Stopwatch)1 SelectedExchangeRateLiveData (de.schildbach.wallet.data.SelectedExchangeRateLiveData)1 WalletBalanceLiveData (de.schildbach.wallet.data.WalletBalanceLiveData)1 WalletLiveData (de.schildbach.wallet.data.WalletLiveData)1 BlockchainState (de.schildbach.wallet.service.BlockchainState)1 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 ArrayList (java.util.ArrayList)1 BlockChain (org.bitcoinj.core.BlockChain)1 BlockStoreException (org.bitcoinj.store.BlockStoreException)1