From 6e1191cf10af9d3ffb1b4fb5c82a96638dbca61e Mon Sep 17 00:00:00 2001 From: Tangem Date: Tue, 19 Jun 2018 13:21:54 +0300 Subject: [PATCH] Updated on 2026-08-14 --- .idea/caches/build_file_checksums.ser | Bin 536 -> 536 bytes app/build.gradle | 8 +- .../tangem/data/network/task/InfuraTask.java | 42 +- .../com/tangem/domain/wallet/TangemCard.java | 17 +- .../dialog/WaitSecurityDelayDialog.java | 129 +- .../presentation/fragment/LoadedWallet.java | 136 +-- .../tangem/presentation/fragment/Main.java | 1071 ++++++++--------- .../main/res/drawable/ic_nfc_white_24dp.xml | 8 + .../res/drawable/ic_wrench_white_24dp.xml | 8 + app/src/main/res/layout/fr_loaded_wallet.xml | 40 +- 10 files changed, 720 insertions(+), 739 deletions(-) create mode 100755 app/src/main/res/drawable/ic_nfc_white_24dp.xml create mode 100755 app/src/main/res/drawable/ic_wrench_white_24dp.xml diff --git a/.idea/caches/build_file_checksums.ser b/.idea/caches/build_file_checksums.ser index 05ff8b2aafb19e8315b7f40ec209bd6106bfe75c..96dd881085d26da2be48544055191bd34b2fecb8 100644 GIT binary patch delta 33 pcmbQiGJ|Ep3>I-ihQ%A_WHSmf6i>b@Y%W{!>3HVa$&HV!DgehV4Nm|7 delta 33 rcmV++0N($Y1egSnm;?gv>))}QYXK3gj%Lt%1Z|eDt@gmZf$hL}2cQvA diff --git a/app/build.gradle b/app/build.gradle index 8b43db7090..aec1870136 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -22,14 +22,14 @@ android { buildTypes { release { -// debuggable false -// minifyEnabled false + debuggable false + minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.debug } debug { -// debuggable true -// minifyEnabled false + debuggable true + minifyEnabled false applicationIdSuffix ".debug" signingConfig signingConfigs.debug } diff --git a/app/src/main/java/com/tangem/data/network/task/InfuraTask.java b/app/src/main/java/com/tangem/data/network/task/InfuraTask.java index f327b6b94d..235c3874a1 100644 --- a/app/src/main/java/com/tangem/data/network/task/InfuraTask.java +++ b/app/src/main/java/com/tangem/data/network/task/InfuraTask.java @@ -28,44 +28,41 @@ import javax.net.ssl.HttpsURLConnection; public class InfuraTask extends AsyncTask> { private Exception exception; private Blockchain blockchain; - public InfuraTask(Blockchain blockchainNet) - { + + public InfuraTask(Blockchain blockchainNet) { blockchain = blockchainNet; } + boolean useOurNode = false; + protected List doInBackground(InfuraRequest... requests) { List result = new ArrayList<>(); for (int i = 0; i < requests.length; i++) { result.add(requests[i]); } - for (InfuraRequest request: result) - { + for (InfuraRequest request : result) { HttpURLConnection httpcon = null; try { URL url = new URL("https://rinkeby.infura.io/AfWg0tmYEX5Kukn2UkKV"); - if(blockchain == Blockchain.Ethereum || blockchain == Blockchain.Token){ - if(useOurNode) { + if (blockchain == Blockchain.Ethereum || blockchain == Blockchain.Token) { + if (useOurNode) { URL tmp = new URL("http://52.230.23.88"); url = new URL(tmp.getProtocol(), tmp.getHost(), 27172, tmp.getFile()); - }else + } else url = new URL("https://mainnet.infura.io/AfWg0tmYEX5Kukn2UkKV"); } - if(useOurNode) - { - httpcon = (HttpURLConnection)url.openConnection(); - } - else - { - httpcon = (HttpsURLConnection)url.openConnection(); + if (useOurNode) { + httpcon = (HttpURLConnection) url.openConnection(); + } else { + httpcon = (HttpsURLConnection) url.openConnection(); } - if(httpcon == null) - { + if (httpcon == null) { request.error = String.format("Cann't connect to %s", url.getHost()); return result; } @@ -75,15 +72,13 @@ public class InfuraTask extends AsyncTask { + int progress = WaitSecurityDelayDialog.this.progressBar.getProgress(); + if (progress < WaitSecurityDelayDialog.this.progressBar.getMax()) { + WaitSecurityDelayDialog.this.progressBar.setProgress(progress + 1000); } }); } @@ -70,22 +67,19 @@ public class WaitSecurityDelayDialog extends DialogFragment { } public void setRemainingTimeout(final int msec) { - progressBar.post(new Runnable() { - @Override - public void run() { - int progress = WaitSecurityDelayDialog.this.progressBar.getProgress(); - if (timer != null) { - // we get delay latency from card for first time - don't change progress by timer, only by card answer - progressBar.setMax(progress + msec); - timer.cancel(); - timer = null; + progressBar.post(() -> { + int progress = WaitSecurityDelayDialog.this.progressBar.getProgress(); + if (timer != null) { + // we get delay latency from card for first time - don't change progress by timer, only by card answer + progressBar.setMax(progress + msec); + timer.cancel(); + timer = null; + } else { + int newProgress = progressBar.getMax() - msec; + if (newProgress > progress) { + progressBar.setProgress(newProgress); } else { - int newProgress = progressBar.getMax() - msec; - if (newProgress > progress) { - progressBar.setProgress(newProgress); - } else { - progressBar.setMax(progress + msec); - } + progressBar.setMax(progress + msec); } } }); @@ -101,68 +95,61 @@ public class WaitSecurityDelayDialog extends DialogFragment { return instance; } - private final static int MinRemainingDelayToShowDialog=1000; - private final static int DelayBeforeShowDialog=5000; + private final static int MinRemainingDelayToShowDialog = 1000; + private final static int DelayBeforeShowDialog = 5000; public static void onReadBeforeRequest(final Activity activity, final int timeout) { - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - if (timerToShowDelayDialog != null || timeout < DelayBeforeShowDialog+MinRemainingDelayToShowDialog) return; - timerToShowDelayDialog = new Timer(); - timerToShowDelayDialog.schedule(new TimerTask() { - @Override - public void run() { - if (WaitSecurityDelayDialog.instance != null) return; - instance = new WaitSecurityDelayDialog(); - instance.setup(timeout, DelayBeforeShowDialog); - instance.setCancelable(false); - instance.show(activity.getFragmentManager(), "WaitSecurityDelayDialog"); - } - }, DelayBeforeShowDialog); - } + activity.runOnUiThread(() -> { + if (timerToShowDelayDialog != null || timeout < DelayBeforeShowDialog + MinRemainingDelayToShowDialog) + return; + timerToShowDelayDialog = new Timer(); + timerToShowDelayDialog.schedule(new TimerTask() { + @Override + public void run() { + if (WaitSecurityDelayDialog.instance != null) return; + instance = new WaitSecurityDelayDialog(); + instance.setup(timeout, DelayBeforeShowDialog); + instance.setCancelable(false); + instance.show(activity.getFragmentManager(), "WaitSecurityDelayDialog"); + } + }, DelayBeforeShowDialog); }); } public static void onReadAfterRequest(final Activity activity) { - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - if (timerToShowDelayDialog == null) return; - timerToShowDelayDialog.cancel(); - timerToShowDelayDialog = null; - } + activity.runOnUiThread(() -> { + if (timerToShowDelayDialog == null) return; + timerToShowDelayDialog.cancel(); + timerToShowDelayDialog = null; }); } public static void OnReadWait(final Activity activity, final int msec) { - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - if (timerToShowDelayDialog != null) { - timerToShowDelayDialog.cancel(); - timerToShowDelayDialog = null; - } + activity.runOnUiThread(() -> { + if (timerToShowDelayDialog != null) { + timerToShowDelayDialog.cancel(); + timerToShowDelayDialog = null; + } - if (msec == 0) { - if (instance != null) { - instance.dismiss(); - instance = null; - } - return; + if (msec == 0) { + if (instance != null) { + instance.dismiss(); + instance = null; } - if (instance == null) { - if( msec>MinRemainingDelayToShowDialog ) { - instance = new WaitSecurityDelayDialog(); - // 1000ms - card delay notification interval - instance.setup(msec + 1000, 1000); - instance.setCancelable(false); - instance.show(activity.getFragmentManager(), "WaitSecurityDelayDialog"); - } - } else { - instance.setRemainingTimeout(msec); + return; + } + if (instance == null) { + if (msec > MinRemainingDelayToShowDialog) { + instance = new WaitSecurityDelayDialog(); + // 1000ms - card delay notification interval + instance.setup(msec + 1000, 1000); + instance.setCancelable(false); + instance.show(activity.getFragmentManager(), "WaitSecurityDelayDialog"); } + } else { + instance.setRemainingTimeout(msec); } }); } -} + +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.java b/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.java index 1c9c790240..12c62f0ceb 100644 --- a/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.java +++ b/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.java @@ -18,6 +18,7 @@ import android.nfc.tech.IsoDep; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; +import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; @@ -59,6 +60,7 @@ import com.tangem.domain.wallet.PINStorage; import com.tangem.domain.wallet.SharedData; import com.tangem.domain.wallet.TangemCard; import com.tangem.presentation.activity.CreateNewWalletActivity; +import com.tangem.presentation.activity.MainActivity; import com.tangem.presentation.activity.PreparePaymentActivity; import com.tangem.presentation.activity.PurgeActivity; import com.tangem.presentation.activity.RequestPINActivity; @@ -98,12 +100,27 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre private static final int REQUEST_CODE_SWAP_PIN = 8; private TangemCard mCard; - private TextView tvCardID, tvBalance, tvOffline, tvBalanceEquivalent, tvWallet, tvInputs, lbInputs, tvPurge, tvError, tvMessage, tvIssuer, tvIssuerData, tvBlockchain, tvLastInput, tvLastOutput, lbLastOutput, tvValidationNode; + private TextView tvCardID; + private TextView tvBalance; + private TextView tvOffline; + private TextView tvBalanceEquivalent; + private TextView tvWallet; + private TextView tvInputs; + private TextView tvError; + private TextView tvMessage; + private TextView tvIssuer; + private TextView tvIssuerData; + private TextView tvBlockchain; + private TextView tvLastInput; + private TextView tvLastOutput; + private TextView lbLastOutput; + private TextView tvValidationNode; private TextView tvHeader, tvCaution; - private ImageView imgLookup; - private TextView tvLookup; private ProgressBar progressBar; - private ImageView ivBlockchain, ivPIN, ivPIN2orSecurityDelay, ivDeveloperVersion, ivQR; + private ImageView ivBlockchain; + private ImageView ivPIN; + private ImageView ivPIN2orSecurityDelay; + private ImageView ivDeveloperVersion; private SwipeRefreshLayout mSwipeRefreshLayout; private List updateTasks = new ArrayList<>(); private NfcManager mNfcManager; @@ -115,6 +132,7 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre private Timer timerHideErrorAndMessage = null; private String newPIN = "", newPIN2 = ""; private AppCompatButton btnLoad, btnExtract; + private FloatingActionButton fabPurge, fabNFC; public LoadedWallet() { @@ -580,7 +598,7 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre public View onCreateView(@NonNull final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fr_loaded_wallet, container, false); - mNfcManager = new NfcManager(this.getActivity(), this); + mNfcManager = new NfcManager(getActivity(), this); mSwipeRefreshLayout = v.findViewById(R.id.swipe_container); tvBalance = v.findViewById(R.id.tvBalance); @@ -588,16 +606,15 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre tvCardID = v.findViewById(R.id.tvCardID); tvWallet = v.findViewById(R.id.tvWallet); tvInputs = v.findViewById(R.id.tvInputs); - lbInputs = v.findViewById(R.id.lbInputs); + TextView lbInputs = v.findViewById(R.id.lbInputs); tvLastOutput = v.findViewById(R.id.tvLastOutput); - lbLastOutput = v.findViewById(R.id.lbLastOutput); tvError = v.findViewById(R.id.tvError); tvMessage = v.findViewById(R.id.tvMessage); tvIssuer = v.findViewById(R.id.tvIssuer); tvIssuerData = v.findViewById(R.id.tvIssuerData); tvHeader = v.findViewById(R.id.tvHeader); tvCaution = v.findViewById(R.id.tvCaution); - imgLookup = v.findViewById(R.id.imgLookup); + ImageView imgLookup = v.findViewById(R.id.imgLookup); tvValidationNode = v.findViewById(R.id.tvValidationNode); progressBar = v.findViewById(R.id.progressBar); tvBlockchain = v.findViewById(R.id.tvBlockchain); @@ -605,43 +622,30 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre ivPIN = v.findViewById(R.id.imgPIN); ivPIN2orSecurityDelay = v.findViewById(R.id.imgPIN2orSecurityDelay); ivDeveloperVersion = v.findViewById(R.id.imgDeveloperVersion); - ivQR = v.findViewById(R.id.qrWallet); - tvLookup = v.findViewById(R.id.tvLookup); - tvPurge = v.findViewById(R.id.tvPurge); + ImageView ivQR = v.findViewById(R.id.qrWallet); + TextView tvLookup = v.findViewById(R.id.tvLookup); + fabPurge = v.findViewById(R.id.fabPurge); + fabNFC = v.findViewById(R.id.fabNFC); btnLoad = v.findViewById(R.id.btnLoad); btnExtract = v.findViewById(R.id.btnExtract); + tvBalanceEquivalent = v.findViewById(R.id.tvBalanceEquivalent); mSwipeRefreshLayout.setOnRefreshListener(this); - mCard = new TangemCard(getActivity().getIntent().getStringExtra("UID")); - mCard.LoadFromBundle(getActivity().getIntent().getExtras().getBundle("Card")); + mCard = new TangemCard(Objects.requireNonNull(getActivity()).getIntent().getStringExtra(TangemCard.EXTRA_CARD)); + mCard.LoadFromBundle(Objects.requireNonNull(getActivity().getIntent().getExtras()).getBundle(TangemCard.EXTRA_CARD)); - if (mCard.getBlockchain() == Blockchain.Token) { - //tvBalance.setLines(2); + if (mCard.getBlockchain() == Blockchain.Token) tvBalance.setSingleLine(false); - } - tvBalanceEquivalent = v.findViewById(R.id.tvBalanceEquivalent); final CoinEngine engine = CoinEngineFactory.Create(mCard.getBlockchain()); - boolean visibleFlag = engine != null ? engine.InOutPutVisible() : true; int visibleIOPuts = visibleFlag ? View.VISIBLE : View.GONE; - if (tvInputs != null) { - tvInputs.setVisibility(visibleIOPuts); - } - if (lbInputs != null) { - lbInputs.setVisibility(visibleIOPuts); - } - - if (tvLastOutput != null) { - tvLastOutput.setVisibility(visibleIOPuts); - } - - if (lbLastOutput != null) { - lbLastOutput.setVisibility(visibleIOPuts); - } + tvInputs.setVisibility(visibleIOPuts); + lbInputs.setVisibility(visibleIOPuts); + tvLastOutput.setVisibility(visibleIOPuts); try { ivQR.setImageBitmap(generateQrCode(Objects.requireNonNull(engine).getShareWalletURI(mCard).toString())); @@ -649,31 +653,44 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre e.printStackTrace(); } - if (imgLookup != null) { - imgLookup.setOnClickListener(v15 -> { - if (!mCard.hasBalanceInfo()) { - return; - } - CoinEngine engineClick = CoinEngineFactory.Create(mCard.getBlockchain()); - - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Objects.requireNonNull(engineClick).getShareWalletURIExplorer(mCard)); - startActivity(browserIntent); - }); + updateViews(); + if (!mCard.hasBalanceInfo()) { + mSwipeRefreshLayout.setRefreshing(true); + mSwipeRefreshLayout.postDelayed(this::onRefresh, 1000); } - if (tvLookup != null) { - tvLookup.setOnClickListener(v14 -> { - if (!mCard.hasBalanceInfo()) { - return; + imgLookup.setOnClickListener(v15 -> { + if (!mCard.hasBalanceInfo()) return; + CoinEngine engineClick = CoinEngineFactory.Create(mCard.getBlockchain()); + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Objects.requireNonNull(engineClick).getShareWalletURIExplorer(mCard)); + startActivity(browserIntent); + }); + + tvLookup.setOnClickListener(v14 -> { + if (!mCard.hasBalanceInfo()) return; + CoinEngine engineClick = CoinEngineFactory.Create(mCard.getBlockchain()); + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Objects.requireNonNull(engineClick).getShareWalletURIExplorer(mCard)); + startActivity(browserIntent); + }); + + tvWallet.setOnClickListener(v12 -> doShareWallet(false)); + + ivQR.setOnClickListener(v1 -> doShareWallet(true)); + + btnLoad.setOnClickListener(v1 -> { + Intent intent = new Intent(Intent.ACTION_VIEW, Objects.requireNonNull(CoinEngineFactory.Create(mCard.getBlockchain())).getShareWalletURI(mCard)); + intent.addCategory(Intent.CATEGORY_DEFAULT); + startActivity(intent); } - CoinEngine engineClick = CoinEngineFactory.Create(mCard.getBlockchain()); + ); - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Objects.requireNonNull(engineClick).getShareWalletURIExplorer(mCard)); - startActivity(browserIntent); - }); - } + fabPurge.setOnClickListener(v16 -> showMenu(fabPurge)); + fabNFC.setOnClickListener(view -> { + Intent intent = new Intent(getContext(), MainActivity.class); + startActivity(intent); + }); btnExtract.setOnClickListener(v13 -> { if (!mCard.hasBalanceInfo()) { @@ -701,23 +718,6 @@ public class LoadedWallet extends Fragment implements SwipeRefreshLayout.OnRefre startActivityForResult(intent, REQUEST_CODE_SEND_PAYMENT); }); - updateViews(); - - if (!mCard.hasBalanceInfo()) { - mSwipeRefreshLayout.setRefreshing(true); - mSwipeRefreshLayout.postDelayed(this::onRefresh, 1000); - } - - tvWallet.setOnClickListener(v12 -> doShareWallet(false)); - ivQR.setOnClickListener(v1 -> doShareWallet(true)); - btnLoad.setOnClickListener(v1 -> { - Intent intent = new Intent(Intent.ACTION_VIEW, Objects.requireNonNull(CoinEngineFactory.Create(mCard.getBlockchain())).getShareWalletURI(mCard)); - intent.addCategory(Intent.CATEGORY_DEFAULT); - startActivity(intent); - } - ); - tvPurge.setOnClickListener(v16 -> showMenu(tvPurge)); - return v; } diff --git a/app/src/main/java/com/tangem/presentation/fragment/Main.java b/app/src/main/java/com/tangem/presentation/fragment/Main.java index b23bbf5d86..132baa0073 100644 --- a/app/src/main/java/com/tangem/presentation/fragment/Main.java +++ b/app/src/main/java/com/tangem/presentation/fragment/Main.java @@ -76,442 +76,58 @@ public class Main extends Fragment implements NfcAdapter.ReaderCallback, CardLis private ArrayList slCardUIDs = new ArrayList<>(); private static final String logTag = "Main"; private ProgressBar progressBar; - private CardListAdapter mCardListAdapter; - - public CardListAdapter getCardListAdapter() { - return mCardListAdapter; - } - private ReadCardInfoTask readCardInfoTask; private SwipeRefreshLayout mSwipeRefreshLayout; //TODO: tmp - List requestTasks = new ArrayList<>(); + private List requestTasks = new ArrayList<>(); - public Main() { - } + private class RateInfoTask extends ExchangeTask { + protected void onPostExecute(List requests) { + super.onPostExecute(requests); + for (ExchangeRequest request : requests) { + if (request.error == null) { + try { -// @Override -// public void onSaveInstanceState(Bundle outState) { -// super.onSaveInstanceState(outState); -// mCardListAdapter.onSaveInstanceState(outState); -// outState.putStringArrayList("slCardUIDs", slCardUIDs); -// } + JSONArray arr = request.getAnswerList(); + for (int i = 0; i < arr.length(); ++i) { + JSONObject obj = arr.getJSONObject(i); + String currency = obj.getString("id"); - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View result = inflater.inflate(R.layout.fr_main, container, false); + boolean stop = false; + boolean stopAlter = false; + if (currency.equals(request.currency)) { + String usd = obj.getString("price_usd"); - mNfcManager = new NfcManager(getActivity(), this); + Float rate = Float.valueOf(usd); + mCardListAdapter.UpdateRate(request.WalletAddress, rate); + stop = true; + } -// NfcManagerComponent component = DaggerNfcManagerComponent.create(); -// mNfcManager = component.getNfcManager(); + if (currency.equals(request.currencyAlter)) { + String usd = obj.getString("price_usd"); - verifyPermissions(); + Float rate = Float.valueOf(usd); + mCardListAdapter.UpdateRateAlter(request.WalletAddress, rate); + stopAlter = true; + } - progressBar = result.findViewById(R.id.progressBar); - progressBar.setProgressTintList(ColorStateList.valueOf(Color.DKGRAY)); - RecyclerView rvCards = result.findViewById(R.id.lvCards); - - rvCards.setLayoutManager(new LinearLayoutManager(getContext())); - mCardListAdapter = new CardListAdapter(inflater, savedInstanceState, this); - rvCards.setAdapter(mCardListAdapter); - if (savedInstanceState != null && savedInstanceState.containsKey("slCardUIDs")) { - slCardUIDs = savedInstanceState.getStringArrayList("slCardUIDs"); - } - - // SwipeRefreshLayout - mSwipeRefreshLayout = result.findViewById(R.id.swipe_container); //TODO: tmp - - if (mSwipeRefreshLayout != null) { - SwipeRefreshLayout.OnRefreshListener onRefreshListener = () -> { - //Update - // Showing refresh animation before making http call - - if (requestTasks.size() > 0) return; - - if (requestTasks.size() > 0) { //TODO: tmp - mSwipeRefreshLayout.setRefreshing(true); - } else { - mSwipeRefreshLayout.setRefreshing(false); - } - }; - mSwipeRefreshLayout.setOnRefreshListener(onRefreshListener); //TODO: tmp - } - - ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { - @Override - public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { - return false; - } - - @Override - public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { - //Remove swiped item from list and notify the RecyclerView - int cardIndex = viewHolder.getAdapterPosition(); - if (cardIndex < 0 || cardIndex >= mCardListAdapter.getItemCount()) return; - slCardUIDs.remove(mCardListAdapter.getCard(cardIndex).getUID()); - if (mCardListAdapter.getCard(cardIndex).getUID() == lastRead_UID) { - lastRead_UID = ""; - } - mCardListAdapter.removeCard(cardIndex); - if (mCardListAdapter.getItemCount() == 0 && getActivity().getClass() == MainActivity.class) { - ((MainActivity) getActivity()).hideCleanButton(); - } - } - }); - - itemTouchHelper.attachToRecyclerView(rvCards); - - if (getActivity() instanceof MainActivity) { - ((MainActivity) getActivity()).setOnCardsClean(this); - ((MainActivity) getActivity()).setNfcAdapterReaderCallback(this); - } - - return result; - } - - private void verifyPermissions() { - NfcManager.verifyPermissions(getActivity()); - if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { - Log.e("QRScanActivity", "User hasn't granted permission to use camera"); - ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_REQUEST_CAMERA_PERMISSIONS); - } - } - - int unsuccessReadCount = 0; - Tag lastTag = null; - - @Override - public void onTagDiscovered(Tag tag) { - try { - // get IsoDep handle and run cardReader thread - final IsoDep isoDep = IsoDep.get(tag); - if (isoDep == null) { - throw new CardProtocol.TangemException(getString(R.string.wrong_tag_err)); - } - - byte UID[] = tag.getId(); - String sUID = Util.byteArrayToHexString(UID); - if (slCardUIDs.indexOf(sUID) != -1) { - Log.d(logTag, "Repeat UID: " + sUID); - mNfcManager.ignoreTag(isoDep.getTag()); - return; - } else { - Log.v(logTag, "UID: " + sUID); - } - -// Log.e(logTag,"setTimeout("+String.valueOf(1000 + 3000 * unsuccessReadCount)+")"); - if (unsuccessReadCount < 2) { - isoDep.setTimeout(2000 + 5000 * unsuccessReadCount); - } else { - isoDep.setTimeout(90000); - } - lastTag = tag; - - readCardInfoTask = new ReadCardInfoTask(isoDep, this); - readCardInfoTask.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void onResume() { - super.onResume(); - mNfcManager.onResume(); - } - - @Override - public void onPause() { - mNfcManager.onPause(); - if (readCardInfoTask != null) { - readCardInfoTask.cancel(true); - } - super.onPause(); - } - - @Override - public void onStop() { - // dismiss enable NFC dialog - mNfcManager.onStop(); - if (readCardInfoTask != null) { - readCardInfoTask.cancel(true); - } - for (RequestWalletInfoTask rt : requestTasks) { - rt.cancel(true); - } - super.onStop(); - } - - public void refreshCard(TangemCard card) { - CoinEngine engine = CoinEngineFactory.Create(card.getBlockchain()); - if (card.getBlockchain() == Blockchain.Ethereum || card.getBlockchain() == Blockchain.EthereumTestNet) { - ETHRequestTask task = new ETHRequestTask(card.getBlockchain()); - InfuraRequest req = InfuraRequest.GetBalance(card.getWallet()); - req.setID(67); - req.setBlockchain(card.getBlockchain()); - InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); - reqNonce.setID(67); - reqNonce.setBlockchain(card.getBlockchain()); - - task.execute(req, reqNonce); - - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "ethereum", "ethereum"); - taskRate.execute(rate); - - } else if (card.getBlockchain() == Blockchain.BitcoinTestNet || card.getBlockchain() == Blockchain.Bitcoin) { - SharedData data = new SharedData(SharedData.COUNT_REQUEST); - for (int i = 0; i < data.allRequest; ++i) { - - String nodeAddress = engine.GetNextNode(card); - int nodePort = engine.GetNextNodePort(card); - RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); - connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); - } - - String nodeAddress = engine.GetNode(card); - int nodePort = engine.GetNodePort(card); - RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); - if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp - requestTasks.add(task); - task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin", "bitcoin"); - taskRate.execute(rate); - - } else if (card.getBlockchain() == Blockchain.BitcoinCashTestNet || card.getBlockchain() == Blockchain.BitcoinCash) { - SharedData data = new SharedData(SharedData.COUNT_REQUEST); - for (int i = 0; i < data.allRequest; ++i) { - - String nodeAddress = engine.GetNextNode(card); - int nodePort = engine.GetNextNodePort(card); - RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); - connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); - } - - String nodeAddress = engine.GetNode(card); - int nodePort = engine.GetNodePort(card); - RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); - if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp - requestTasks.add(task); - task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin-cash", "bitcoin-cash"); - taskRate.execute(rate); - - } else if (card.getBlockchain() == Blockchain.Token) { - ETHRequestTask updateETH = new ETHRequestTask(card.getBlockchain()); - InfuraRequest reqETH = InfuraRequest.GetTokenBalance(card.getWallet(), engine.GetContractAddress(card), engine.GetTokenDecimals(card)); - reqETH.setID(67); - reqETH.setBlockchain(card.getBlockchain()); - - - InfuraRequest reqBalance = InfuraRequest.GetBalance(card.getWallet()); - reqBalance.setID(67); - reqBalance.setBlockchain(card.getBlockchain()); - - - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "basic-attention-token", "ethereum"); - taskRate.execute(rate); - - InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); - reqNonce.setID(67); - reqNonce.setBlockchain(card.getBlockchain()); - - updateETH.execute(reqETH, reqNonce, reqBalance); - } - } - - public void addCard(final TangemCard card) { - if (mCardListAdapter != null) { - Objects.requireNonNull(getActivity()).runOnUiThread(() -> { - unsuccessReadCount = 0; - slCardUIDs.add(0, card.getUID()); - mCardListAdapter.addCard(card); - - CoinEngine engine = CoinEngineFactory.Create(card.getBlockchain()); - - if (card.getStatus() == TangemCard.Status.Loaded) { - - if (card.getBlockchain() == Blockchain.Ethereum || card.getBlockchain() == Blockchain.EthereumTestNet) { - ETHRequestTask task = new ETHRequestTask(card.getBlockchain()); - InfuraRequest req = InfuraRequest.GetBalance(card.getWallet()); - req.setID(67); - req.setBlockchain(card.getBlockchain()); - InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); - reqNonce.setID(67); - reqNonce.setBlockchain(card.getBlockchain()); - - task.execute(req, reqNonce); - - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "ethereum", "ethereum"); - taskRate.execute(rate); - - } else if (card.getBlockchain() == Blockchain.BitcoinTestNet || card.getBlockchain() == Blockchain.Bitcoin) { - SharedData data = new SharedData(SharedData.COUNT_REQUEST); - - for (int i = 0; i < data.allRequest; ++i) { - String nodeAddress = engine.GetNextNode(card); - int nodePort = engine.GetNextNodePort(card); - - RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); - connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); + if (stop && stopAlter) { + break; + } } - String nodeAddress = engine.GetNode(card); - int nodePort = engine.GetNodePort(card); - RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); - if (mSwipeRefreshLayout != null) - mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp - - requestTasks.add(task); - task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin", "bitcoin"); - taskRate.execute(rate); - - } else if (card.getBlockchain() == Blockchain.BitcoinCashTestNet || card.getBlockchain() == Blockchain.BitcoinCash) { - SharedData data = new SharedData(SharedData.COUNT_REQUEST); - - for (int i = 0; i < data.allRequest; ++i) { - String nodeAddress = engine.GetNextNode(card); - int nodePort = engine.GetNextNodePort(card); - - RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); - connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); - } - - String nodeAddress = engine.GetNode(card); - int nodePort = engine.GetNodePort(card); - - RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); - if (mSwipeRefreshLayout != null) - mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp - - requestTasks.add(task); - task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin-cash", "bitcoin-cash"); - taskRate.execute(rate); - - } else if (card.getBlockchain() == Blockchain.Token) { - ETHRequestTask updateETH = new ETHRequestTask(card.getBlockchain()); - InfuraRequest reqETH = InfuraRequest.GetTokenBalance(card.getWallet(), engine.GetContractAddress(card), engine.GetTokenDecimals(card)); - reqETH.setID(67); - reqETH.setBlockchain(card.getBlockchain()); - - - InfuraRequest reqBalance = InfuraRequest.GetBalance(card.getWallet()); - reqBalance.setID(67); - reqBalance.setBlockchain(card.getBlockchain()); - - - RateInfoTask taskRate = new RateInfoTask(); - ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "basic-attention-token", "ethereum"); - taskRate.execute(rate); - - InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); - reqNonce.setID(67); - reqNonce.setBlockchain(card.getBlockchain()); - - updateETH.execute(reqETH, reqNonce, reqBalance); + //mCardListAdapter.UpdateWalletBalance(mWalletAddress, balance, l.toString(10)); + } catch (JSONException e) { + e.printStackTrace(); } } - if (getActivity().getClass() == MainActivity.class) { - ((MainActivity) getActivity()).showCleanButton(); - } - }); - } - } - - @Override - public void onViewCard(Bundle cardInfo) { - - if (mSwipeRefreshLayout != null) - mSwipeRefreshLayout.setRefreshing(false); //TODO: tmp - - String UID = cardInfo.getString("UID"); - TangemCard card = new TangemCard(UID); - card.LoadFromBundle(cardInfo.getBundle("Card")); - - Intent intent; - if (card.getStatus() == TangemCard.Status.Empty) { - intent = new Intent(getActivity(), EmptyWalletActivity.class); -// Toast.makeText(getContext(), "1", Toast.LENGTH_SHORT).show(); - } else if (card.getStatus() == TangemCard.Status.Loaded) { - intent = new Intent(getActivity(), LoadedWalletActivity.class); -// Toast.makeText(getContext(), "2", Toast.LENGTH_SHORT).show(); - } else if (card.getStatus() == TangemCard.Status.NotPersonalized || card.getStatus() == TangemCard.Status.Purged) { -// Toast.makeText(getContext(), "3", Toast.LENGTH_SHORT).show(); - return; - } else { - intent = new Intent(getActivity(), LoadedWalletActivity.class); -// Toast.makeText(getContext(), "4", Toast.LENGTH_SHORT).show(); - } - - intent.putExtras(cardInfo); - startActivityForResult(intent, REQUEST_CODE_SHOW_CARD_ACTIVITY); - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - Log.d(logTag, "ActivityResult: requestCode = " + requestCode + ", resultCode = " + resultCode); - // если пришло ОК - if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_SHOW_CARD_ACTIVITY) { - if (data != null && data.getExtras().containsKey("UID")) { - final TangemCard card = new TangemCard(data.getStringExtra("UID")); - card.LoadFromBundle(data.getBundleExtra("Card")); - if (data.getStringExtra("modification").equals("delete")) { - mCardListAdapter.removeCard(card); - for (int i = 0; i < slCardUIDs.size(); i++) { - if (slCardUIDs.get(i).equals(card.getUID())) { - slCardUIDs.remove(i); - break; - } - } - if (mCardListAdapter.getItemCount() == 0 && getActivity().getClass() == MainActivity.class) { - ((MainActivity) getActivity()).hideCleanButton(); - } - } else if (data.getStringExtra("modification").equals("update")) { - mCardListAdapter.updateCard(card); - } else if (data.getStringExtra("modification").equals("updateAndViewCard")) { - mCardListAdapter.updateCard(card); - onViewCard(data.getExtras()); - } - } - } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_ENTER_PIN_ACTIVITY) { - if (lastTag != null) onTagDiscovered(lastTag); } } - @Override - public void doClean() { - mCardListAdapter.clearCards(); - slCardUIDs.clear(); - for (RequestWalletInfoTask rt : requestTasks) { - rt.cancel(true); - } - lastRead_UID = ""; - } - - public void doEnterPIN() { - Intent intent = new Intent(getContext(), RequestPINActivity.class); - intent.putExtra("mode", RequestPINActivity.Mode.RequestPIN.toString()); - startActivityForResult(intent, REQUEST_CODE_ENTER_PIN_ACTIVITY); - } - - private static String lastRead_UID = ""; - private static ArrayList lastRead_UnsuccessfullPINs = new ArrayList<>(); - private static TangemCard.EncryptionMode lastRead_Encryption = null; - private class ReadCardInfoTask extends Thread { - IsoDep mIsoDep; CardProtocol.Notifications mNotifications; private boolean isCancelled = false; @@ -654,103 +270,6 @@ public class Main extends Fragment implements NfcAdapter.ReaderCallback, CardLis } - public void OnReadStart(CardProtocol cardProtocol) { - progressBar.post(new Runnable() { - @Override - public void run() { - progressBar.setVisibility(View.VISIBLE); - progressBar.setProgress(5); - } - }); - } - - public void OnReadFinish(final CardProtocol cardProtocol) { - - readCardInfoTask = null; - - if (cardProtocol != null) { - if (cardProtocol.getError() == null) { - progressBar.post(() -> { - progressBar.setProgress(100); - progressBar.setProgressTintList(ColorStateList.valueOf(Color.GREEN)); - addCard(cardProtocol.getCard()); - }); - } else { - // remove last UIDs because of error and no card read - progressBar.post(() -> { - if (getContext() != null) { - Toast.makeText(getContext(), R.string.try_to_scan_again, Toast.LENGTH_LONG).show(); - unsuccessReadCount++; - progressBar.setProgress(100); - progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED)); - slCardUIDs.remove(cardProtocol.getCard().getUID()); - if (cardProtocol.getError() instanceof CardProtocol.TangemException_InvalidPIN) { - doEnterPIN(); - } else if (cardProtocol.getError() instanceof CardProtocol.TangemException_ExtendedLengthNotSupported) { - if (!NoExtendedLengthSupportDialog.allreadyShowed) { - new NoExtendedLengthSupportDialog().show(Objects.requireNonNull(getActivity()).getFragmentManager(), NoExtendedLengthSupportDialog.TAG); - } - } else { - lastTag = null; - } - } - }); - } - } - - progressBar.postDelayed(() -> { - try { - progressBar.setProgress(0); - progressBar.setProgressTintList(ColorStateList.valueOf(Color.DKGRAY)); - progressBar.setVisibility(View.INVISIBLE); - } catch (Exception e) { - e.printStackTrace(); - } - }, 500); - } - - public void OnReadProgress(CardProtocol protocol, final int progress) { - progressBar.post(new Runnable() { - @Override - public void run() { - progressBar.setProgress(progress); - } - }); - } - - public void OnReadCancel() { - - readCardInfoTask = null; - - progressBar.postDelayed(new Runnable() { - @Override - public void run() { - try { - progressBar.setProgress(0); - progressBar.setProgressTintList(ColorStateList.valueOf(Color.DKGRAY)); - progressBar.setVisibility(View.INVISIBLE); - } catch (Exception e) { - e.printStackTrace(); - } - } - }, 500); - } - - - public void OnReadWait(final int msec) { - WaitSecurityDelayDialog.OnReadWait(getActivity(), msec); - } - - @Override - public void OnReadBeforeRequest(int timeout) { - WaitSecurityDelayDialog.onReadBeforeRequest(getActivity(), timeout); - } - - @Override - public void OnReadAfterRequest() { - WaitSecurityDelayDialog.onReadAfterRequest(getActivity()); - } - private class RequestWalletInfoTask extends ElectrumTask { public RequestWalletInfoTask(String host, int port) { super(host, port); @@ -1010,48 +529,512 @@ public class Main extends Fragment implements NfcAdapter.ReaderCallback, CardLis } - private class RateInfoTask extends ExchangeTask { - protected void onPostExecute(List requests) { - super.onPostExecute(requests); - for (ExchangeRequest request : requests) { - if (request.error == null) { - try { + public Main() { + } - JSONArray arr = request.getAnswerList(); - for (int i = 0; i < arr.length(); ++i) { - JSONObject obj = arr.getJSONObject(i); - String currency = obj.getString("id"); + public CardListAdapter getCardListAdapter() { + return mCardListAdapter; + } - boolean stop = false; - boolean stopAlter = false; - if (currency.equals(request.currency)) { - String usd = obj.getString("price_usd"); +// @Override +// public void onSaveInstanceState(Bundle outState) { +// super.onSaveInstanceState(outState); +// mCardListAdapter.onSaveInstanceState(outState); +// outState.putStringArrayList("slCardUIDs", slCardUIDs); +// } - Float rate = Float.valueOf(usd); - mCardListAdapter.UpdateRate(request.WalletAddress, rate); - stop = true; - } + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View result = inflater.inflate(R.layout.fr_main, container, false); - if (currency.equals(request.currencyAlter)) { - String usd = obj.getString("price_usd"); + mNfcManager = new NfcManager(getActivity(), this); - Float rate = Float.valueOf(usd); - mCardListAdapter.UpdateRateAlter(request.WalletAddress, rate); - stopAlter = true; - } +// NfcManagerComponent component = DaggerNfcManagerComponent.create(); +// mNfcManager = component.getNfcManager(); - if (stop && stopAlter) { - break; - } - } + verifyPermissions(); + progressBar = result.findViewById(R.id.progressBar); + progressBar.setProgressTintList(ColorStateList.valueOf(Color.DKGRAY)); + RecyclerView rvCards = result.findViewById(R.id.lvCards); - //mCardListAdapter.UpdateWalletBalance(mWalletAddress, balance, l.toString(10)); - } catch (JSONException e) { - e.printStackTrace(); - } + rvCards.setLayoutManager(new LinearLayoutManager(getContext())); + mCardListAdapter = new CardListAdapter(inflater, savedInstanceState, this); + rvCards.setAdapter(mCardListAdapter); + if (savedInstanceState != null && savedInstanceState.containsKey("slCardUIDs")) { + slCardUIDs = savedInstanceState.getStringArrayList("slCardUIDs"); + } + + // SwipeRefreshLayout + mSwipeRefreshLayout = result.findViewById(R.id.swipe_container); //TODO: tmp + + if (mSwipeRefreshLayout != null) { + SwipeRefreshLayout.OnRefreshListener onRefreshListener = () -> { + //Update + // Showing refresh animation before making http call + + if (requestTasks.size() > 0) return; + + if (requestTasks.size() > 0) { //TODO: tmp + mSwipeRefreshLayout.setRefreshing(true); + } else { + mSwipeRefreshLayout.setRefreshing(false); + } + }; + mSwipeRefreshLayout.setOnRefreshListener(onRefreshListener); //TODO: tmp + } + + ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { + @Override + public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { + return false; + } + + @Override + public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { + //Remove swiped item from list and notify the RecyclerView + int cardIndex = viewHolder.getAdapterPosition(); + if (cardIndex < 0 || cardIndex >= mCardListAdapter.getItemCount()) return; + slCardUIDs.remove(mCardListAdapter.getCard(cardIndex).getUID()); + if (mCardListAdapter.getCard(cardIndex).getUID() == lastRead_UID) { + lastRead_UID = ""; + } + mCardListAdapter.removeCard(cardIndex); + if (mCardListAdapter.getItemCount() == 0 && getActivity().getClass() == MainActivity.class) { + ((MainActivity) getActivity()).hideCleanButton(); } } + }); + + itemTouchHelper.attachToRecyclerView(rvCards); + + if (getActivity() instanceof MainActivity) { + ((MainActivity) getActivity()).setOnCardsClean(this); + ((MainActivity) getActivity()).setNfcAdapterReaderCallback(this); + } + + return result; + } + + int unsuccessReadCount = 0; + Tag lastTag = null; + + @Override + public void onResume() { + super.onResume(); + mNfcManager.onResume(); + } + + @Override + public void onPause() { + mNfcManager.onPause(); + if (readCardInfoTask != null) { + readCardInfoTask.cancel(true); + } + super.onPause(); + } + + @Override + public void onStop() { + // dismiss enable NFC dialog + mNfcManager.onStop(); + if (readCardInfoTask != null) { + readCardInfoTask.cancel(true); + } + for (RequestWalletInfoTask rt : requestTasks) { + rt.cancel(true); + } + super.onStop(); + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.d(logTag, "ActivityResult: requestCode = " + requestCode + ", resultCode = " + resultCode); + if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_SHOW_CARD_ACTIVITY) { + if (data != null && Objects.requireNonNull(data.getExtras()).containsKey("UID")) { + final TangemCard card = new TangemCard(data.getStringExtra("UID")); + card.LoadFromBundle(data.getBundleExtra("Card")); + if (data.getStringExtra("modification").equals("delete")) { + mCardListAdapter.removeCard(card); + for (int i = 0; i < slCardUIDs.size(); i++) { + if (slCardUIDs.get(i).equals(card.getUID())) { + slCardUIDs.remove(i); + break; + } + } + if (mCardListAdapter.getItemCount() == 0 && getActivity().getClass() == MainActivity.class) { + ((MainActivity) getActivity()).hideCleanButton(); + } + } else if (data.getStringExtra("modification").equals("update")) { + mCardListAdapter.updateCard(card); + } else if (data.getStringExtra("modification").equals("updateAndViewCard")) { + mCardListAdapter.updateCard(card); + onViewCard(data.getExtras()); + } + + } + } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_ENTER_PIN_ACTIVITY) { + if (lastTag != null) onTagDiscovered(lastTag); + } + } + + @Override + public void onTagDiscovered(Tag tag) { + try { + // get IsoDep handle and run cardReader thread + final IsoDep isoDep = IsoDep.get(tag); + if (isoDep == null) { + throw new CardProtocol.TangemException(getString(R.string.wrong_tag_err)); + } + + byte UID[] = tag.getId(); + String sUID = Util.byteArrayToHexString(UID); + if (slCardUIDs.indexOf(sUID) != -1) { + Log.d(logTag, "Repeat UID: " + sUID); + mNfcManager.ignoreTag(isoDep.getTag()); + return; + } else { + Log.v(logTag, "UID: " + sUID); + } + +// Log.e(logTag,"setTimeout("+String.valueOf(1000 + 3000 * unsuccessReadCount)+")"); + if (unsuccessReadCount < 2) { + isoDep.setTimeout(2000 + 5000 * unsuccessReadCount); + } else { + isoDep.setTimeout(90000); + } + lastTag = tag; + + readCardInfoTask = new ReadCardInfoTask(isoDep, this); + readCardInfoTask.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void onViewCard(Bundle cardInfo) { + + if (mSwipeRefreshLayout != null) + mSwipeRefreshLayout.setRefreshing(false); //TODO: tmp + + String UID = cardInfo.getString("UID"); + TangemCard card = new TangemCard(UID); + card.LoadFromBundle(cardInfo.getBundle("Card")); + + Intent intent; + if (card.getStatus() == TangemCard.Status.Empty) { + intent = new Intent(getActivity(), EmptyWalletActivity.class); + Toast.makeText(getContext(), "1", Toast.LENGTH_SHORT).show(); + } else if (card.getStatus() == TangemCard.Status.Loaded) { + intent = new Intent(getActivity(), LoadedWalletActivity.class); + Toast.makeText(getContext(), "2", Toast.LENGTH_SHORT).show(); + } else if (card.getStatus() == TangemCard.Status.NotPersonalized || card.getStatus() == TangemCard.Status.Purged) { + Toast.makeText(getContext(), "3", Toast.LENGTH_SHORT).show(); + return; + } else { + intent = new Intent(getActivity(), LoadedWalletActivity.class); + Toast.makeText(getContext(), "4", Toast.LENGTH_SHORT).show(); + } + + intent.putExtras(cardInfo); + startActivityForResult(intent, REQUEST_CODE_SHOW_CARD_ACTIVITY); + } + + + @Override + public void doClean() { + mCardListAdapter.clearCards(); + slCardUIDs.clear(); + for (RequestWalletInfoTask rt : requestTasks) { + rt.cancel(true); + } + lastRead_UID = ""; + } + + private static String lastRead_UID = ""; + private static ArrayList lastRead_UnsuccessfullPINs = new ArrayList<>(); + private static TangemCard.EncryptionMode lastRead_Encryption = null; + + + public void OnReadStart(CardProtocol cardProtocol) { + progressBar.post(() -> { + progressBar.setVisibility(View.VISIBLE); + progressBar.setProgress(5); + }); + } + + public void OnReadFinish(final CardProtocol cardProtocol) { + readCardInfoTask = null; + if (cardProtocol != null) { + if (cardProtocol.getError() == null) { + progressBar.post(() -> { + progressBar.setProgress(100); + progressBar.setProgressTintList(ColorStateList.valueOf(Color.GREEN)); + addCard(cardProtocol.getCard()); + }); + } else { + // remove last UIDs because of error and no card read + progressBar.post(() -> { + if (getContext() != null) { + Toast.makeText(getContext(), R.string.try_to_scan_again, Toast.LENGTH_LONG).show(); + unsuccessReadCount++; + progressBar.setProgress(100); + progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED)); + slCardUIDs.remove(cardProtocol.getCard().getUID()); + if (cardProtocol.getError() instanceof CardProtocol.TangemException_InvalidPIN) { + doEnterPIN(); + } else if (cardProtocol.getError() instanceof CardProtocol.TangemException_ExtendedLengthNotSupported) { + if (!NoExtendedLengthSupportDialog.allreadyShowed) { + new NoExtendedLengthSupportDialog().show(Objects.requireNonNull(getActivity()).getFragmentManager(), NoExtendedLengthSupportDialog.TAG); + } + } else { + lastTag = null; + } + } + }); + } + } + + progressBar.postDelayed(() -> { + try { + progressBar.setProgress(0); + progressBar.setProgressTintList(ColorStateList.valueOf(Color.DKGRAY)); + progressBar.setVisibility(View.INVISIBLE); + } catch (Exception e) { + e.printStackTrace(); + } + }, 500); + } + + public void OnReadProgress(CardProtocol protocol, final int progress) { + progressBar.post(() -> progressBar.setProgress(progress)); + } + + public void OnReadCancel() { + readCardInfoTask = null; + progressBar.postDelayed(() -> { + try { + progressBar.setProgress(0); + progressBar.setProgressTintList(ColorStateList.valueOf(Color.DKGRAY)); + progressBar.setVisibility(View.INVISIBLE); + } catch (Exception e) { + e.printStackTrace(); + } + }, 500); + } + + + public void OnReadWait(final int msec) { + WaitSecurityDelayDialog.OnReadWait(getActivity(), msec); + } + + @Override + public void OnReadBeforeRequest(int timeout) { + WaitSecurityDelayDialog.onReadBeforeRequest(getActivity(), timeout); + } + + @Override + public void OnReadAfterRequest() { + WaitSecurityDelayDialog.onReadAfterRequest(getActivity()); + } + + private void refreshCard(TangemCard card) { + CoinEngine engine = CoinEngineFactory.Create(card.getBlockchain()); + if (card.getBlockchain() == Blockchain.Ethereum || card.getBlockchain() == Blockchain.EthereumTestNet) { + ETHRequestTask task = new ETHRequestTask(card.getBlockchain()); + InfuraRequest req = InfuraRequest.GetBalance(card.getWallet()); + req.setID(67); + req.setBlockchain(card.getBlockchain()); + InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); + reqNonce.setID(67); + reqNonce.setBlockchain(card.getBlockchain()); + + task.execute(req, reqNonce); + + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "ethereum", "ethereum"); + taskRate.execute(rate); + + } else if (card.getBlockchain() == Blockchain.BitcoinTestNet || card.getBlockchain() == Blockchain.Bitcoin) { + SharedData data = new SharedData(SharedData.COUNT_REQUEST); + for (int i = 0; i < data.allRequest; ++i) { + + String nodeAddress = engine.GetNextNode(card); + int nodePort = engine.GetNextNodePort(card); + RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); + connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); + } + + String nodeAddress = engine.GetNode(card); + int nodePort = engine.GetNodePort(card); + RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); + if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp + requestTasks.add(task); + task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin", "bitcoin"); + taskRate.execute(rate); + + } else if (card.getBlockchain() == Blockchain.BitcoinCashTestNet || card.getBlockchain() == Blockchain.BitcoinCash) { + SharedData data = new SharedData(SharedData.COUNT_REQUEST); + for (int i = 0; i < data.allRequest; ++i) { + + String nodeAddress = engine.GetNextNode(card); + int nodePort = engine.GetNextNodePort(card); + RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); + connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); + } + + String nodeAddress = engine.GetNode(card); + int nodePort = engine.GetNodePort(card); + RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); + if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp + requestTasks.add(task); + task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin-cash", "bitcoin-cash"); + taskRate.execute(rate); + + } else if (card.getBlockchain() == Blockchain.Token) { + ETHRequestTask updateETH = new ETHRequestTask(card.getBlockchain()); + InfuraRequest reqETH = InfuraRequest.GetTokenBalance(card.getWallet(), engine.GetContractAddress(card), engine.GetTokenDecimals(card)); + reqETH.setID(67); + reqETH.setBlockchain(card.getBlockchain()); + + + InfuraRequest reqBalance = InfuraRequest.GetBalance(card.getWallet()); + reqBalance.setID(67); + reqBalance.setBlockchain(card.getBlockchain()); + + + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "basic-attention-token", "ethereum"); + taskRate.execute(rate); + + InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); + reqNonce.setID(67); + reqNonce.setBlockchain(card.getBlockchain()); + + updateETH.execute(reqETH, reqNonce, reqBalance); + } + } + + private void addCard(final TangemCard card) { + if (mCardListAdapter != null) { + Objects.requireNonNull(getActivity()).runOnUiThread(() -> { + unsuccessReadCount = 0; + slCardUIDs.add(0, card.getUID()); + mCardListAdapter.addCard(card); + + CoinEngine engine = CoinEngineFactory.Create(card.getBlockchain()); + + if (card.getStatus() == TangemCard.Status.Loaded) { + + if (card.getBlockchain() == Blockchain.Ethereum || card.getBlockchain() == Blockchain.EthereumTestNet) { + ETHRequestTask task = new ETHRequestTask(card.getBlockchain()); + InfuraRequest req = InfuraRequest.GetBalance(card.getWallet()); + req.setID(67); + req.setBlockchain(card.getBlockchain()); + InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); + reqNonce.setID(67); + reqNonce.setBlockchain(card.getBlockchain()); + + task.execute(req, reqNonce); + + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "ethereum", "ethereum"); + taskRate.execute(rate); + + } else if (card.getBlockchain() == Blockchain.BitcoinTestNet || card.getBlockchain() == Blockchain.Bitcoin) { + SharedData data = new SharedData(SharedData.COUNT_REQUEST); + + for (int i = 0; i < data.allRequest; ++i) { + String nodeAddress = engine.GetNextNode(card); + int nodePort = engine.GetNextNodePort(card); + + RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); + connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); + } + + String nodeAddress = engine.GetNode(card); + int nodePort = engine.GetNodePort(card); + + RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); + if (mSwipeRefreshLayout != null) + mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp + + requestTasks.add(task); + task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin", "bitcoin"); + taskRate.execute(rate); + + } else if (card.getBlockchain() == Blockchain.BitcoinCashTestNet || card.getBlockchain() == Blockchain.BitcoinCash) { + SharedData data = new SharedData(SharedData.COUNT_REQUEST); + + for (int i = 0; i < data.allRequest; ++i) { + String nodeAddress = engine.GetNextNode(card); + int nodePort = engine.GetNextNodePort(card); + + RequestWalletInfoTask connectTaskEx = new RequestWalletInfoTask(nodeAddress, nodePort, data); + connectTaskEx.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.CheckBalance(card.getWallet())); + } + + String nodeAddress = engine.GetNode(card); + int nodePort = engine.GetNodePort(card); + + RequestWalletInfoTask task = new RequestWalletInfoTask(nodeAddress, nodePort); + if (mSwipeRefreshLayout != null) + mSwipeRefreshLayout.setRefreshing(true); //TODO: tmp + + requestTasks.add(task); + task.execute(ElectrumRequest.ListUnspent(card.getWallet()), ElectrumRequest.ListHistory(card.getWallet())); + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "bitcoin-cash", "bitcoin-cash"); + taskRate.execute(rate); + + } else if (card.getBlockchain() == Blockchain.Token) { + ETHRequestTask updateETH = new ETHRequestTask(card.getBlockchain()); + InfuraRequest reqETH = InfuraRequest.GetTokenBalance(card.getWallet(), engine.GetContractAddress(card), engine.GetTokenDecimals(card)); + reqETH.setID(67); + reqETH.setBlockchain(card.getBlockchain()); + + + InfuraRequest reqBalance = InfuraRequest.GetBalance(card.getWallet()); + reqBalance.setID(67); + reqBalance.setBlockchain(card.getBlockchain()); + + + RateInfoTask taskRate = new RateInfoTask(); + ExchangeRequest rate = ExchangeRequest.GetRate(card.getWallet(), "basic-attention-token", "ethereum"); + taskRate.execute(rate); + + InfuraRequest reqNonce = InfuraRequest.GetOutTransactionCount(card.getWallet()); + reqNonce.setID(67); + reqNonce.setBlockchain(card.getBlockchain()); + + updateETH.execute(reqETH, reqNonce, reqBalance); + } + } + if (getActivity().getClass() == MainActivity.class) { + ((MainActivity) getActivity()).showCleanButton(); + } + }); + } + } + + private void doEnterPIN() { + Intent intent = new Intent(getContext(), RequestPINActivity.class); + intent.putExtra("mode", RequestPINActivity.Mode.RequestPIN.toString()); + startActivityForResult(intent, REQUEST_CODE_ENTER_PIN_ACTIVITY); + } + + private void verifyPermissions() { + NfcManager.verifyPermissions(getActivity()); + if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + Log.e("QRScanActivity", "User hasn't granted permission to use camera"); + ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_REQUEST_CAMERA_PERMISSIONS); } } diff --git a/app/src/main/res/drawable/ic_nfc_white_24dp.xml b/app/src/main/res/drawable/ic_nfc_white_24dp.xml new file mode 100755 index 0000000000..fe750229c4 --- /dev/null +++ b/app/src/main/res/drawable/ic_nfc_white_24dp.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_wrench_white_24dp.xml b/app/src/main/res/drawable/ic_wrench_white_24dp.xml new file mode 100755 index 0000000000..8c15c96d9b --- /dev/null +++ b/app/src/main/res/drawable/ic_wrench_white_24dp.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fr_loaded_wallet.xml b/app/src/main/res/layout/fr_loaded_wallet.xml index 0746b8db34..499b83ffcc 100644 --- a/app/src/main/res/layout/fr_loaded_wallet.xml +++ b/app/src/main/res/layout/fr_loaded_wallet.xml @@ -215,8 +215,7 @@ android:gravity="top|center" android:orientation="horizontal" android:paddingLeft="8dp" - android:paddingRight="8dp" - > + android:paddingRight="8dp"> - + + +