Revert network changes

This commit is contained in:
dtvv 2018-09-05 19:36:27 -05:00
parent e0903c0a26
commit 5fb847ba1c
4 changed files with 155 additions and 227 deletions

View file

@ -8,6 +8,7 @@ import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import cy.agorise.crystalwallet.application.constant.BitsharesConstant;
import cy.agorise.crystalwallet.dao.BitsharesAssetDao; import cy.agorise.crystalwallet.dao.BitsharesAssetDao;
import cy.agorise.crystalwallet.dao.CryptoCoinBalanceDao; import cy.agorise.crystalwallet.dao.CryptoCoinBalanceDao;
import cy.agorise.crystalwallet.dao.CryptoCurrencyDao; import cy.agorise.crystalwallet.dao.CryptoCurrencyDao;
@ -78,17 +79,15 @@ public abstract class GrapheneApiGenerator {
/** /**
* This is used for manager each listener in the subscription thread * This is used for manager each listener in the subscription thread
*/ */
private static HashMap<Long, SubscriptionListener> currentBitsharesListener = new HashMap<>(); private static HashMap<Long,SubscriptionListener> currentBitsharesListener = new HashMap<>();
/** /**
* Retrieves the data of an account searching by it's id * Retrieves the data of an account searching by it's id
* *
* @param accountId The accountId to retrieve * @param accountId The accountId to retrieve
* @param request The Api request object, to answer this petition * @param request The Api request object, to answer this petition
*/ */
public static void getAccountById(String accountId, final ApiRequest request) { public static void getAccountById(String accountId, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetAccounts(accountId, WebSocketThread thread = new WebSocketThread(new GetAccounts(accountId,
new WitnessResponseListener() { new WitnessResponseListener() {
@Override @Override
@ -97,7 +96,7 @@ public abstract class GrapheneApiGenerator {
List list = (List) response.result; List list = (List) response.result;
if (list.size() > 0) { if (list.size() > 0) {
if (list.get(0).getClass() == AccountProperties.class) { if (list.get(0).getClass() == AccountProperties.class) {
request.getListener().success(list.get(0), request.getId()); request.getListener().success(list.get(0),request.getId());
return; return;
} }
} }
@ -109,7 +108,7 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -119,20 +118,17 @@ public abstract class GrapheneApiGenerator {
* @param address The address to retrieve * @param address The address to retrieve
* @param request The Api request object, to answer this petition * @param request The Api request object, to answer this petition
*/ */
public static void getAccountByOwnerOrActiveAddress(Address address, final ApiRequest request) { public static void getAccountByOwnerOrActiveAddress(Address address, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetKeyReferences(address, true, WebSocketThread thread = new WebSocketThread(new GetKeyReferences(address, true,
new WitnessResponseListener() { new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
final List<List<UserAccount>> resp = (List<List<UserAccount>>) response.result; final List<List<UserAccount>> resp = (List<List<UserAccount>>) response.result;
if (resp.size() > 0) { if(resp.size() > 0){
List<UserAccount> accounts = resp.get(0); List<UserAccount> accounts = resp.get(0);
if (accounts.size() > 0) { if(accounts.size() > 0){
for (UserAccount account : accounts) { for(UserAccount account : accounts) {
request.getListener().success(account, request.getId()); request.getListener().success(account,request.getId());}}}
}
}
}
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
@ -140,7 +136,7 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -149,25 +145,25 @@ public abstract class GrapheneApiGenerator {
* Gets the Transaction for an Account * Gets the Transaction for an Account
* *
* @param accountGrapheneId The account id to search * @param accountGrapheneId The account id to search
* @param start The start index of the transaction list * @param start The start index of the transaction list
* @param stop The stop index of the transaction list * @param stop The stop index of the transaction list
* @param limit the maximun transactions to retrieve * @param limit the maximun transactions to retrieve
* @param request The Api request object, to answer this petition * @param request The Api request object, to answer this petition
*/ */
public static void getAccountTransaction(String accountGrapheneId, int start, int stop, public static void getAccountTransaction(String accountGrapheneId, int start, int stop,
int limit, final ApiRequest request) { int limit, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetRelativeAccountHistory(new UserAccount(accountGrapheneId), WebSocketThread thread = new WebSocketThread(new GetRelativeAccountHistory(new UserAccount(accountGrapheneId),
start, limit, stop, new WitnessResponseListener() { start, limit, stop, new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
request.getListener().success(response.result, request.getId()); request.getListener().success(response.result,request.getId());
} }
@Override @Override
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -175,18 +171,18 @@ public abstract class GrapheneApiGenerator {
* Retrieves the account id by the name of the account * Retrieves the account id by the name of the account
* *
* @param accountName The account Name to find * @param accountName The account Name to find
* @param request The Api request object, to answer this petition * @param request The Api request object, to answer this petition
*/ */
public static void getAccountByName(String accountName, final ApiRequest request) { public static void getAccountByName(String accountName, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetAccountByName(accountName, WebSocketThread thread = new WebSocketThread(new GetAccountByName(accountName,
new WitnessResponseListener() { new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
AccountProperties accountProperties = (AccountProperties) response.result; AccountProperties accountProperties = (AccountProperties)response.result;
if (accountProperties == null) { if(accountProperties == null){
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} else { }else{
request.getListener().success(accountProperties, request.getId()); request.getListener().success(accountProperties,request.getId());
} }
} }
@ -194,7 +190,7 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -202,18 +198,18 @@ public abstract class GrapheneApiGenerator {
* Retrieves the account id by the name of the account * Retrieves the account id by the name of the account
* *
* @param accountName The account Name to find * @param accountName The account Name to find
* @param request The Api request object, to answer this petition * @param request The Api request object, to answer this petition
*/ */
public static void getAccountIdByName(String accountName, final ApiRequest request) { public static void getAccountIdByName(String accountName, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetAccountByName(accountName, WebSocketThread thread = new WebSocketThread(new GetAccountByName(accountName,
new WitnessResponseListener() { new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
AccountProperties accountProperties = (AccountProperties) response.result; AccountProperties accountProperties = (AccountProperties)response.result;
if (accountProperties == null) { if(accountProperties == null){
request.getListener().success(null, request.getId()); request.getListener().success(null,request.getId());
} else { }else{
request.getListener().success(accountProperties.id, request.getId()); request.getListener().success(accountProperties.id,request.getId());
} }
} }
@ -221,7 +217,7 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -229,23 +225,23 @@ public abstract class GrapheneApiGenerator {
* Broadcast a transaction, this is use for sending funds * Broadcast a transaction, this is use for sending funds
* *
* @param transaction The graphene transaction * @param transaction The graphene transaction
* @param feeAsset The feeAseet, this needs only the id of the asset * @param feeAsset The feeAseet, this needs only the id of the asset
* @param request the api request object, to answer this petition * @param request the api request object, to answer this petition
*/ */
public static void broadcastTransaction(Transaction transaction, Asset feeAsset, public static void broadcastTransaction(Transaction transaction, Asset feeAsset,
final ApiRequest request) { final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new TransactionBroadcastSequence(transaction, WebSocketThread thread = new WebSocketThread(new TransactionBroadcastSequence(transaction,
feeAsset, new WitnessResponseListener() { feeAsset, new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
request.getListener().success(true, request.getId()); request.getListener().success(true,request.getId());
} }
@Override @Override
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -253,20 +249,20 @@ public abstract class GrapheneApiGenerator {
* This gets the asset information using only the asset name * This gets the asset information using only the asset name
* *
* @param assetNames The list of the names of the assets to be retrieve * @param assetNames The list of the names of the assets to be retrieve
* @param request the api request object, to answer this petition * @param request the api request object, to answer this petition
*/ */
public static void getAssetByName(ArrayList<String> assetNames, final ApiRequest request) { public static void getAssetByName(ArrayList<String> assetNames, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new LookupAssetSymbols(assetNames, true, WebSocketThread thread = new WebSocketThread(new LookupAssetSymbols(assetNames,true,
new WitnessResponseListener() { new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
List<Asset> assets = (List<Asset>) response.result; List<Asset> assets = (List<Asset>) response.result;
if (assets.size() <= 0) { if(assets.size() <= 0){
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} else { }else{
ArrayList<BitsharesAsset> responseAssets = new ArrayList<>(); ArrayList<BitsharesAsset> responseAssets = new ArrayList<>();
for (Asset asset : assets) { for(Asset asset: assets){
//TODO asset type //TODO asset type
BitsharesAsset.Type assetType = BitsharesAsset.Type.UIA; BitsharesAsset.Type assetType = BitsharesAsset.Type.UIA;
/*if(asset.getAssetType().equals(Asset.AssetType.CORE_ASSET)){ /*if(asset.getAssetType().equals(Asset.AssetType.CORE_ASSET)){
@ -279,10 +275,10 @@ public abstract class GrapheneApiGenerator {
assetType = BitsharesAsset.Type.PREDICTION_MARKET; assetType = BitsharesAsset.Type.PREDICTION_MARKET;
}*/ }*/
BitsharesAsset responseAsset = new BitsharesAsset(asset.getSymbol(), BitsharesAsset responseAsset = new BitsharesAsset(asset.getSymbol(),
asset.getPrecision(), asset.getObjectId(), assetType); asset.getPrecision(),asset.getObjectId(),assetType);
responseAssets.add(responseAsset); responseAssets.add(responseAsset);
} }
request.getListener().success(responseAssets, request.getId()); request.getListener().success(responseAssets,request.getId());
} }
} }
@ -290,32 +286,31 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
/** /**
* Gets the asset ifnormation using the id of the net * Gets the asset ifnormation using the id of the net
*
* @param assetIds The list of the ids to retrieve * @param assetIds The list of the ids to retrieve
* @param request the api request object, to answer this petition * @param request the api request object, to answer this petition
*/ */
public static void getAssetById(ArrayList<String> assetIds, final ApiRequest request) { public static void getAssetById(ArrayList<String> assetIds, final ApiRequest request){
ArrayList<Asset> assets = new ArrayList<>(); ArrayList<Asset> assets = new ArrayList<>();
for (String assetId : assetIds) { for(String assetId : assetIds){
Asset asset = new Asset(assetId); Asset asset = new Asset(assetId);
assets.add(asset); assets.add(asset);
} }
WebSocketThread thread = new WebSocketThread(new LookupAssetSymbols(assets, true, new WitnessResponseListener() { WebSocketThread thread = new WebSocketThread(new LookupAssetSymbols(assets,true, new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
List<Asset> assets = (List<Asset>) response.result; List<Asset> assets = (List<Asset>) response.result;
if (assets.size() <= 0) { if(assets.size() <= 0){
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} else { }else{
ArrayList<BitsharesAsset> responseAssets = new ArrayList<>(); ArrayList<BitsharesAsset> responseAssets = new ArrayList<>();
for (Asset asset : assets) { for(Asset asset: assets){
//TODO asset type //TODO asset type
BitsharesAsset.Type assetType = BitsharesAsset.Type.UIA; BitsharesAsset.Type assetType = BitsharesAsset.Type.UIA;
/*if(asset.getAssetType().equals(Asset.AssetType.CORE_ASSET)){ /*if(asset.getAssetType().equals(Asset.AssetType.CORE_ASSET)){
@ -328,10 +323,10 @@ public abstract class GrapheneApiGenerator {
assetType = BitsharesAsset.Type.PREDICTION_MARKET; assetType = BitsharesAsset.Type.PREDICTION_MARKET;
}*/ }*/
BitsharesAsset responseAsset = new BitsharesAsset(asset.getSymbol(), BitsharesAsset responseAsset = new BitsharesAsset(asset.getSymbol(),
asset.getPrecision(), asset.getObjectId(), assetType); asset.getPrecision(),asset.getObjectId(),assetType);
responseAssets.add(responseAsset); responseAssets.add(responseAsset);
} }
request.getListener().success(responseAssets, request.getId()); request.getListener().success(responseAssets,request.getId());
} }
} }
@ -339,20 +334,20 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
/** /**
* Subscribe a bitshares account to receive real time updates * Subscribe a bitshares account to receive real time updates
* *
* @param accountId The id opf the database of the account * @param accountId The id opf the database of the account
* @param accountBitsharesId The bitshares id of the account * @param accountBitsharesId The bitshares id of the account
* @param context The android context of this application * @param context The android context of this application
*/ */
public static void subscribeBitsharesAccount(final long accountId, final String accountBitsharesId, public static void subscribeBitsharesAccount(final long accountId, final String accountBitsharesId,
final Context context) { final Context context){
if (!currentBitsharesListener.containsKey(accountId)) { if(!currentBitsharesListener.containsKey(accountId)){
CrystalDatabase db = CrystalDatabase.getAppDatabase(context); CrystalDatabase db = CrystalDatabase.getAppDatabase(context);
final BitsharesAssetDao bitsharesAssetDao = db.bitsharesAssetDao(); final BitsharesAssetDao bitsharesAssetDao = db.bitsharesAssetDao();
final CryptoCurrencyDao cryptoCurrencyDao = db.cryptoCurrencyDao(); final CryptoCurrencyDao cryptoCurrencyDao = db.cryptoCurrencyDao();
@ -365,15 +360,15 @@ public abstract class GrapheneApiGenerator {
@Override @Override
public void onSubscriptionUpdate(SubscriptionResponse response) { public void onSubscriptionUpdate(SubscriptionResponse response) {
List<Serializable> updatedObjects = (List<Serializable>) response.params.get(1); List<Serializable> updatedObjects = (List<Serializable>) response.params.get(1);
if (updatedObjects.size() > 0) { if(updatedObjects.size() > 0){
for (Serializable update : updatedObjects) { for(Serializable update : updatedObjects){
if (update instanceof BroadcastedTransaction) { if(update instanceof BroadcastedTransaction){
BroadcastedTransaction transactionUpdate = (BroadcastedTransaction) update; BroadcastedTransaction transactionUpdate = (BroadcastedTransaction) update;
for (BaseOperation operation : transactionUpdate.getTransaction().getOperations()) { for(BaseOperation operation : transactionUpdate.getTransaction().getOperations()){
if (operation instanceof TransferOperation) { if(operation instanceof TransferOperation){
final TransferOperation tOperation = (TransferOperation) operation; final TransferOperation tOperation = (TransferOperation) operation;
if (tOperation.getFrom().getObjectId().equals(accountBitsharesId) || tOperation.getTo().getObjectId().equals(accountBitsharesId)) { if(tOperation.getFrom().getObjectId().equals(accountBitsharesId) || tOperation.getTo().getObjectId().equals(accountBitsharesId)){
GrapheneApiGenerator.getAccountBalance(accountId, accountBitsharesId, context); GrapheneApiGenerator.getAccountBalance(accountId,accountBitsharesId,context);
final CryptoCoinTransaction transaction = new CryptoCoinTransaction(); final CryptoCoinTransaction transaction = new CryptoCoinTransaction();
transaction.setAccountId(accountId); transaction.setAccountId(accountId);
transaction.setAmount(tOperation.getAssetAmount().getAmount().longValue()); transaction.setAmount(tOperation.getAssetAmount().getAmount().longValue());
@ -384,13 +379,13 @@ public abstract class GrapheneApiGenerator {
@Override @Override
public void success(Object answer, int idPetition) { public void success(Object answer, int idPetition) {
ArrayList<BitsharesAsset> assets = (ArrayList<BitsharesAsset>) answer; ArrayList<BitsharesAsset> assets = (ArrayList<BitsharesAsset>) answer;
for (BitsharesAsset asset : assets) { for(BitsharesAsset asset : assets){
long idCryptoCurrency = cryptoCurrencyDao.insertCryptoCurrency(asset)[0]; long idCryptoCurrency = cryptoCurrencyDao.insertCryptoCurrency(asset)[0];
BitsharesAssetInfo info = new BitsharesAssetInfo(asset); BitsharesAssetInfo info = new BitsharesAssetInfo(asset);
info.setCryptoCurrencyId(idCryptoCurrency); info.setCryptoCurrencyId(idCryptoCurrency);
asset.setId((int) idCryptoCurrency); asset.setId((int)idCryptoCurrency);
bitsharesAssetDao.insertBitsharesAssetInfo(info); bitsharesAssetDao.insertBitsharesAssetInfo(info);
saveTransaction(transaction, cryptoCurrencyDao.getById(info.getCryptoCurrencyId()), accountBitsharesId, tOperation, context); saveTransaction(transaction,cryptoCurrencyDao.getById(info.getCryptoCurrencyId()),accountBitsharesId,tOperation,context);
} }
} }
@ -401,9 +396,9 @@ public abstract class GrapheneApiGenerator {
}); });
ArrayList<String> assets = new ArrayList<>(); ArrayList<String> assets = new ArrayList<>();
assets.add(tOperation.getAssetAmount().getAsset().getObjectId()); assets.add(tOperation.getAssetAmount().getAsset().getObjectId());
GrapheneApiGenerator.getAssetById(assets, assetRequest); GrapheneApiGenerator.getAssetById(assets,assetRequest);
} else { }else{
saveTransaction(transaction, cryptoCurrencyDao.getById(info.getCryptoCurrencyId()), accountBitsharesId, tOperation, context); saveTransaction(transaction,cryptoCurrencyDao.getById(info.getCryptoCurrencyId()),accountBitsharesId,tOperation,context);
} }
} }
} }
@ -415,62 +410,56 @@ public abstract class GrapheneApiGenerator {
} }
}; };
currentBitsharesListener.put(accountId, balanceListener); currentBitsharesListener.put(accountId,balanceListener);
bitsharesSubscriptionHub.addSubscriptionListener(balanceListener); bitsharesSubscriptionHub.addSubscriptionListener(balanceListener);
try {
if (!subscriptionThread.isConnected() && !subscriptionThread.isAlive()) {
subscriptionThread.start(); if(!subscriptionThread.isConnected()){
subscriptionThread.start();
} else if (bitsharesSubscriptionHub != null && !bitsharesSubscriptionHub.isSubscribed()) { }else if(!bitsharesSubscriptionHub.isSubscribed()){
bitsharesSubscriptionHub.resubscribe(); bitsharesSubscriptionHub.resubscribe();
}
} catch (Exception e) {
e.printStackTrace();
} }
} }
} }
/** /**
* Function to save a transaction retrieved from the update * Function to save a transaction retrieved from the update
* * @param transaction The transaction db object
* @param transaction The transaction db object * @param currency The currency of the transaccion
* @param currency The currency of the transaccion
* @param accountBitsharesId The id of the account in the bitshares network * @param accountBitsharesId The id of the account in the bitshares network
* @param tOperation The transfer operation fetched from the update * @param tOperation The transfer operation fetched from the update
* @param context The context of this app * @param context The context of this app
*/ */
private static void saveTransaction(CryptoCoinTransaction transaction, CryptoCurrency currency, private static void saveTransaction(CryptoCoinTransaction transaction, CryptoCurrency currency,
String accountBitsharesId, TransferOperation tOperation, String accountBitsharesId, TransferOperation tOperation ,
Context context) { Context context){
transaction.setIdCurrency((int) currency.getId()); transaction.setIdCurrency((int)currency.getId());
transaction.setConfirmed(true); //graphene transaction are always confirmed transaction.setConfirmed(true); //graphene transaction are always confirmed
transaction.setFrom(tOperation.getFrom().getObjectId()); transaction.setFrom(tOperation.getFrom().getObjectId());
transaction.setInput(!tOperation.getFrom().getObjectId().equals(accountBitsharesId)); transaction.setInput(!tOperation.getFrom().getObjectId().equals(accountBitsharesId));
transaction.setTo(tOperation.getTo().getObjectId()); transaction.setTo(tOperation.getTo().getObjectId());
transaction.setDate(new Date()); transaction.setDate(new Date());
CrystalDatabase.getAppDatabase(context).transactionDao().insertTransaction(transaction); CrystalDatabase.getAppDatabase(context).transactionDao().insertTransaction(transaction);
if (transaction.getInput()) { if(transaction.getInput()){
CryptoNetEvents.getInstance().fireEvent(new ReceivedFundsCryptoNetEvent(transaction.getAccount(), currency, transaction.getAmount())); CryptoNetEvents.getInstance().fireEvent(new ReceivedFundsCryptoNetEvent(transaction.getAccount(),currency,transaction.getAmount()));
} }
} }
/** /**
* Cancels all bitshares account subscriptions * Cancels all bitshares account subscriptions
*/ */
public static void cancelBitsharesAccountSubscriptions() { public static void cancelBitsharesAccountSubscriptions(){
bitsharesSubscriptionHub.cancelSubscriptions(); bitsharesSubscriptionHub.cancelSubscriptions();
} }
/** /**
* Retrieve the account balance of an account * Retrieve the account balance of an account
* *
* @param accountId The dataabase id of the account * @param accountId The dataabase id of the account
* @param accountGrapheneId The bitshares id of the account * @param accountGrapheneId The bitshares id of the account
* @param context The android context of this application * @param context The android context of this application
*/ */
public static void getAccountBalance(final long accountId, final String accountGrapheneId, public static void getAccountBalance(final long accountId, final String accountGrapheneId,
final Context context) { final Context context){
CrystalDatabase db = CrystalDatabase.getAppDatabase(context); CrystalDatabase db = CrystalDatabase.getAppDatabase(context);
final CryptoCoinBalanceDao balanceDao = db.cryptoCoinBalanceDao(); final CryptoCoinBalanceDao balanceDao = db.cryptoCoinBalanceDao();
@ -481,19 +470,19 @@ public abstract class GrapheneApiGenerator {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
List<AssetAmount> balances = (List<AssetAmount>) response.result; List<AssetAmount> balances = (List<AssetAmount>) response.result;
for (final AssetAmount balance : balances) { for(final AssetAmount balance : balances){
final CryptoCoinBalance ccBalance = new CryptoCoinBalance(); final CryptoCoinBalance ccBalance = new CryptoCoinBalance();
ccBalance.setAccountId(accountId); ccBalance.setAccountId(accountId);
ccBalance.setBalance(balance.getAmount().longValue()); ccBalance.setBalance(balance.getAmount().longValue());
BitsharesAssetInfo assetInfo = bitsharesAssetDao.getBitsharesAssetInfoById(balance.getAsset().getObjectId()); BitsharesAssetInfo assetInfo = bitsharesAssetDao.getBitsharesAssetInfoById(balance.getAsset().getObjectId());
if (assetInfo == null) { if(assetInfo == null ){
ArrayList<String> idAssets = new ArrayList<>(); ArrayList<String> idAssets = new ArrayList<>();
idAssets.add(balance.getAsset().getObjectId()); idAssets.add(balance.getAsset().getObjectId());
ApiRequest getAssetRequest = new ApiRequest(1, new ApiRequestListener() { ApiRequest getAssetRequest = new ApiRequest(1, new ApiRequestListener() {
@Override @Override
public void success(Object answer, int idPetition) { public void success(Object answer, int idPetition) {
List<BitsharesAsset> assets = (List<BitsharesAsset>) answer; List<BitsharesAsset> assets = (List<BitsharesAsset>) answer;
for (BitsharesAsset asset : assets) { for(BitsharesAsset asset : assets) {
BitsharesAssetInfo info = new BitsharesAssetInfo(asset); BitsharesAssetInfo info = new BitsharesAssetInfo(asset);
long[] cryptoCurrencyId = cryptoCurrencyDao.insertCryptoCurrency((CryptoCurrency) asset); long[] cryptoCurrencyId = cryptoCurrencyDao.insertCryptoCurrency((CryptoCurrency) asset);
info.setCryptoCurrencyId(cryptoCurrencyId[0]); info.setCryptoCurrencyId(cryptoCurrencyId[0]);
@ -507,9 +496,9 @@ public abstract class GrapheneApiGenerator {
public void fail(int idPetition) { public void fail(int idPetition) {
} }
}); });
getAssetById(idAssets, getAssetRequest); getAssetById(idAssets,getAssetRequest);
} else { }else {
ccBalance.setCryptoCurrencyId(assetInfo.getCryptoCurrencyId()); ccBalance.setCryptoCurrencyId(assetInfo.getCryptoCurrencyId());
balanceDao.insertCryptoCoinBalance(ccBalance); balanceDao.insertCryptoCoinBalance(ccBalance);
@ -521,7 +510,7 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
@ -531,15 +520,15 @@ public abstract class GrapheneApiGenerator {
* Gets the date time of a block header * Gets the date time of a block header
* *
* @param blockHeader The block header to retrieve the date time * @param blockHeader The block header to retrieve the date time
* @param request the api request object, to answer this petition * @param request the api request object, to answer this petition
*/ */
public static void getBlockHeaderTime(long blockHeader, final ApiRequest request) { public static void getBlockHeaderTime(long blockHeader, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetBlockHeader(blockHeader, new WitnessResponseListener() { WebSocketThread thread = new WebSocketThread(new GetBlockHeader(blockHeader, new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
if (response == null) { if(response == null){
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} else { }else {
request.getListener().success(response.result, request.getId()); request.getListener().success(response.result, request.getId());
} }
} }
@ -548,7 +537,7 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); }),CryptoNetManager.getURL(CryptoNet.BITSHARES));
thread.start(); thread.start();
} }
@ -556,21 +545,21 @@ public abstract class GrapheneApiGenerator {
/** /**
* Gets a single equivalent value * Gets a single equivalent value
* *
* @param baseId The base asset bistshares id * @param baseId The base asset bistshares id
* @param quoteId the quote asset bitshares id * @param quoteId the quote asset bitshares id
* @param request the api request object, to answer this petition * @param request the api request object, to answer this petition
*/ */
public static void getEquivalentValue(final String baseId, String quoteId, final ApiRequest request) { public static void getEquivalentValue(final String baseId, String quoteId, final ApiRequest request){
WebSocketThread thread = new WebSocketThread(new GetLimitOrders(baseId, quoteId, 10, WebSocketThread thread = new WebSocketThread(new GetLimitOrders(baseId, quoteId, 10,
new WitnessResponseListener() { new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
List<LimitOrder> orders = (List<LimitOrder>) response.result; List<LimitOrder> orders = (List<LimitOrder>) response.result;
if (orders.size() <= 0) { if(orders.size()<= 0){
//TODO indirect equivalent value //TODO indirect equivalent value
} }
for (LimitOrder order : orders) { for(LimitOrder order : orders){
if (order.getSellPrice().base.getAsset().getBitassetId().equals(baseId)) { if(order.getSellPrice().base.getAsset().getBitassetId().equals(baseId)) {
Converter converter = new Converter(); Converter converter = new Converter();
double equiValue = converter.getConversionRate(order.getSellPrice(), double equiValue = converter.getConversionRate(order.getSellPrice(),
Converter.BASE_TO_QUOTE); Converter.BASE_TO_QUOTE);
@ -584,23 +573,23 @@ public abstract class GrapheneApiGenerator {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
request.getListener().fail(request.getId()); request.getListener().fail(request.getId());
} }
}), CryptoNetManager.getURL(CryptoNet.BITSHARES)); //todo change equivalent url for current server url }), BitsharesConstant.EQUIVALENT_URL); //todo change equivalent url for current server url
thread.start(); thread.start();
} }
/** /**
* Gets equivalent value and store it on the database * Gets equivalent value and store it on the database
* *
* @param baseAsset The baset asset as a bitshares asset, it needs the CryptoCurrency and thge BitsharesInfo * @param baseAsset The baset asset as a bitshares asset, it needs the CryptoCurrency and thge BitsharesInfo
* @param quoteAssets The list of the qutoe assets as a full bitshares asset object * @param quoteAssets The list of the qutoe assets as a full bitshares asset object
* @param context The android context of this application * @param context The android context of this application
*/ */
public static void getEquivalentValue(BitsharesAsset baseAsset, public static void getEquivalentValue(BitsharesAsset baseAsset,
final List<BitsharesAsset> quoteAssets, final Context context) { final List<BitsharesAsset> quoteAssets, final Context context){
for (BitsharesAsset quoteAsset : quoteAssets) { for(BitsharesAsset quoteAsset : quoteAssets){
WebSocketThread thread = new WebSocketThread(new GetLimitOrders(baseAsset.getBitsharesId(), WebSocketThread thread = new WebSocketThread(new GetLimitOrders(baseAsset.getBitsharesId(),
quoteAsset.getBitsharesId(), 10, new EquivalentValueListener(baseAsset, quoteAsset.getBitsharesId(), 10, new EquivalentValueListener(baseAsset,
quoteAsset, context)), CryptoNetManager.getURL(CryptoNet.BITSHARES)); //todo change equivalent url for current server url quoteAsset,context)), BitsharesConstant.EQUIVALENT_URL); //todo change equivalent url for current server url
thread.start(); thread.start();
} }
} }
@ -609,25 +598,25 @@ public abstract class GrapheneApiGenerator {
* Retrieves the equivalent value from a list of assets to a base asset * Retrieves the equivalent value from a list of assets to a base asset
* *
* @param baseAssetName The base asset to use * @param baseAssetName The base asset to use
* @param quoteAssets The list of quotes assets to query * @param quoteAssets The list of quotes assets to query
* @param context The Context of this Application * @param context The Context of this Application
*/ */
public static void getEquivalentValue(String baseAssetName, final List<BitsharesAsset> quoteAssets, final Context context) { public static void getEquivalentValue(String baseAssetName, final List<BitsharesAsset> quoteAssets, final Context context){
CrystalDatabase db = CrystalDatabase.getAppDatabase(context); CrystalDatabase db = CrystalDatabase.getAppDatabase(context);
final CryptoCurrencyDao cryptoCurrencyDao = db.cryptoCurrencyDao(); final CryptoCurrencyDao cryptoCurrencyDao = db.cryptoCurrencyDao();
final BitsharesAssetDao bitsharesAssetDao = db.bitsharesAssetDao(); final BitsharesAssetDao bitsharesAssetDao = db.bitsharesAssetDao();
CryptoCurrency baseCurrency = cryptoCurrencyDao.getByName(baseAssetName); CryptoCurrency baseCurrency = cryptoCurrencyDao.getByName(baseAssetName);
BitsharesAssetInfo info = null; BitsharesAssetInfo info = null;
if (baseCurrency != null) { if(baseCurrency != null){
info = db.bitsharesAssetDao().getBitsharesAssetInfo(baseCurrency.getId()); info = db.bitsharesAssetDao().getBitsharesAssetInfo(baseCurrency.getId());
} }
if (baseCurrency == null || info == null) { if(baseCurrency == null || info == null){
ApiRequest getAssetRequest = new ApiRequest(1, new ApiRequestListener() { ApiRequest getAssetRequest = new ApiRequest(1, new ApiRequestListener() {
@Override @Override
public void success(Object answer, int idPetition) { public void success(Object answer, int idPetition) {
if (answer instanceof BitsharesAsset) { if(answer instanceof BitsharesAsset){
BitsharesAssetInfo info = new BitsharesAssetInfo((BitsharesAsset) answer); BitsharesAssetInfo info = new BitsharesAssetInfo((BitsharesAsset) answer);
long cryptoCurrencyId = cryptoCurrencyDao.insertCryptoCurrency((CryptoCurrency) answer)[0]; long cryptoCurrencyId = cryptoCurrencyDao.insertCryptoCurrency((CryptoCurrency)answer )[0];
info.setCryptoCurrencyId(cryptoCurrencyId); info.setCryptoCurrencyId(cryptoCurrencyId);
bitsharesAssetDao.insertBitsharesAssetInfo(info); bitsharesAssetDao.insertBitsharesAssetInfo(info);
GrapheneApiGenerator.getEquivalentValue((BitsharesAsset) answer, quoteAssets, context); GrapheneApiGenerator.getEquivalentValue((BitsharesAsset) answer, quoteAssets, context);
@ -641,12 +630,12 @@ public abstract class GrapheneApiGenerator {
}); });
ArrayList<String> names = new ArrayList<>(); ArrayList<String> names = new ArrayList<>();
names.add(baseAssetName); names.add(baseAssetName);
GrapheneApiGenerator.getAssetByName(names, getAssetRequest); GrapheneApiGenerator.getAssetByName(names,getAssetRequest);
} else { }else {
BitsharesAsset baseAsset = new BitsharesAsset(baseCurrency); BitsharesAsset baseAsset = new BitsharesAsset(baseCurrency);
baseAsset.loadInfo(info); baseAsset.loadInfo(info);
getEquivalentValue(baseAsset, quoteAssets, context); getEquivalentValue(baseAsset,quoteAssets,context);
} }
@ -655,7 +644,7 @@ public abstract class GrapheneApiGenerator {
/** /**
* Listener of the equivalent value the answer is stored in the database, for use in conjuntion with LiveData * Listener of the equivalent value the answer is stored in the database, for use in conjuntion with LiveData
*/ */
private static class EquivalentValueListener implements WitnessResponseListener { private static class EquivalentValueListener implements WitnessResponseListener{
/** /**
* The base asset * The base asset
*/ */
@ -678,10 +667,10 @@ public abstract class GrapheneApiGenerator {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
List<LimitOrder> orders = (List<LimitOrder>) response.result; List<LimitOrder> orders = (List<LimitOrder>) response.result;
if (orders.size() <= 0) { if(orders.size()<= 0){
//TODO indirect equivalent value //TODO indirect equivalent value
} }
for (LimitOrder order : orders) { for(LimitOrder order : orders){
try { try {
//if (order.getSellPrice().base.getAsset().getBitassetId().equals(baseAsset.getBitsharesId())) { //if (order.getSellPrice().base.getAsset().getBitassetId().equals(baseAsset.getBitsharesId())) {
Converter converter = new Converter(); Converter converter = new Converter();
@ -692,7 +681,7 @@ public abstract class GrapheneApiGenerator {
CrystalDatabase.getAppDatabase(context).cryptoCurrencyEquivalenceDao().insertCryptoCurrencyEquivalence(equivalence); CrystalDatabase.getAppDatabase(context).cryptoCurrencyEquivalenceDao().insertCryptoCurrencyEquivalence(equivalence);
break; break;
//} //}
} catch (Exception e) { }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -703,4 +692,5 @@ public abstract class GrapheneApiGenerator {
} }
} }
} }

View file

@ -1,6 +1,5 @@
package cy.agorise.crystalwallet.network; package cy.agorise.crystalwallet.network;
import cy.agorise.crystalwallet.apigenerator.GrapheneApiGenerator;
import cy.agorise.crystalwallet.enums.CryptoNet; import cy.agorise.crystalwallet.enums.CryptoNet;
import cy.agorise.graphenej.interfaces.WitnessResponseListener; import cy.agorise.graphenej.interfaces.WitnessResponseListener;
import cy.agorise.graphenej.models.BaseResponse; import cy.agorise.graphenej.models.BaseResponse;
@ -24,21 +23,15 @@ public class BitsharesCryptoNetVerifier extends CryptoNetVerifier {
private final String CHAIN_ID = "9cf6f255a208100d2bb275a3c52f4b1589b7ec9c9bfc2cb2a5fe6411295106d8";//testnet private final String CHAIN_ID = "9cf6f255a208100d2bb275a3c52f4b1589b7ec9c9bfc2cb2a5fe6411295106d8";//testnet
//private final String CHAIN_ID = "4018d7844c78f6a6c41c6a552b898022310fc5dec06da467ee7905a8dad512c8";//mainnet //private final String CHAIN_ID = "4018d7844c78f6a6c41c6a552b898022310fc5dec06da467ee7905a8dad512c8";//mainnet
@Override
public void checkURL(final String url) {
public BitsharesCryptoNetVerifier(){
/**/
final long startTime = System.currentTimeMillis(); final long startTime = System.currentTimeMillis();
thread = new WebSocketThread(new GetChainId(new WitnessResponseListener() { WebSocketThread thread = new WebSocketThread(new GetChainId(new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
if(response.result instanceof String) { if(response.result instanceof String) {
if(response.result.equals(CHAIN_ID)) { if(response.result.equals(CHAIN_ID)) {
CryptoNetManager.verifiedCryptoNetURL(cryptoNet, null, System.currentTimeMillis() - startTime); CryptoNetManager.verifiedCryptoNetURL(cryptoNet, url, System.currentTimeMillis() - startTime);
}else{ }else{
System.out.println(" BitsharesCryptoNetVerifier Error we are not in the net current chain id " + response.result + " excepted " + CHAIN_ID); System.out.println(" BitsharesCryptoNetVerifier Error we are not in the net current chain id " + response.result + " excepted " + CHAIN_ID);
//TODO handle error bad chain //TODO handle error bad chain
@ -50,15 +43,8 @@ public class BitsharesCryptoNetVerifier extends CryptoNetVerifier {
public void onError(BaseResponse.Error error) { public void onError(BaseResponse.Error error) {
//TODO handle error //TODO handle error
} }
}),null); }),url);
thread.start();
}
@Override
public void checkURL(final String url) {
thread.setmUrl(url); //Set the url
thread.start(); //Run the thread connection
} }
@Override @Override

View file

@ -1,8 +1,5 @@
package cy.agorise.crystalwallet.network; package cy.agorise.crystalwallet.network;
import android.app.Activity;
import cy.agorise.crystalwallet.apigenerator.GrapheneApiGenerator;
import cy.agorise.crystalwallet.enums.CryptoNet; import cy.agorise.crystalwallet.enums.CryptoNet;
/** /**
@ -15,14 +12,6 @@ import cy.agorise.crystalwallet.enums.CryptoNet;
public abstract class CryptoNetVerifier { public abstract class CryptoNetVerifier {
/*
* Contains the worker connection thread
*/
protected WebSocketThread thread;
static CryptoNetVerifier getNetworkVerify(CryptoNet cryptoNet){ static CryptoNetVerifier getNetworkVerify(CryptoNet cryptoNet){
if(cryptoNet.getLabel().equals(CryptoNet.BITSHARES.getLabel())){ if(cryptoNet.getLabel().equals(CryptoNet.BITSHARES.getLabel())){
return new BitsharesCryptoNetVerifier(); return new BitsharesCryptoNetVerifier();
@ -33,9 +22,4 @@ public abstract class CryptoNetVerifier {
public abstract void checkURL(final String url); public abstract void checkURL(final String url);
public abstract String getChainId(); public abstract String getChainId();
public WebSocketThread getThread() {
return thread;
}
} }

View file

@ -3,6 +3,7 @@ package cy.agorise.crystalwallet.network;
import android.util.Log; import android.util.Log;
import com.neovisionaries.ws.client.WebSocket; import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory; import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketListener; import com.neovisionaries.ws.client.WebSocketListener;
@ -33,11 +34,6 @@ public class WebSocketThread extends Thread {
private boolean canChange = true; private boolean canChange = true;
/*
* Object needed for socket connection
* */
private WebSocketFactory factory;
/** /**
* Basic constructor, * Basic constructor,
* *
@ -47,27 +43,16 @@ public class WebSocketThread extends Thread {
* @param url The url to connect * @param url The url to connect
*/ */
public WebSocketThread(WebSocketListener webSocketListener, String url) { public WebSocketThread(WebSocketListener webSocketListener, String url) {
try {
/* WebSocketFactory factory = new WebSocketFactory().setConnectionTimeout(5000);
* The listener always can be setted this.mUrl = url;
* */ this.mWebSocketListener = webSocketListener;
this.mWebSocketListener = webSocketListener; this.mWebSocket = factory.createSocket(this.mUrl);
this.mWebSocket.addListener(this.mWebSocketListener);
/* } catch (IOException e) {
* Log.e(TAG, "IOException. Msg: "+e.getMessage());
* If at this point the url is not defined, this will be set after } catch(NullPointerException e){
* */ Log.e(TAG, "NullPointerException at WebsocketWorkerThreas. Msg: "+e.getMessage());
if(url!=null){
try {
factory = new WebSocketFactory().setConnectionTimeout(5000);
this.mUrl = url;
this.mWebSocket = factory.createSocket(this.mUrl);
this.mWebSocket.addListener(this.mWebSocketListener);
} catch (IOException e) {
Log.e(TAG, "IOException. Msg: "+e.getMessage());
} catch(NullPointerException e){
Log.e(TAG, "NullPointerException at WebsocketWorkerThreas. Msg: "+e.getMessage());
}
} }
} }
@ -125,28 +110,16 @@ public class WebSocketThread extends Thread {
@Override @Override
public void run() { public void run() {
canChange = false; canChange = false;
// Moves the current Thread into the background // Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try { try {
/*
* If the initialization of the socket comes after
* */
if(factory==null){
factory = new WebSocketFactory().setConnectionTimeout(5000);
this.mWebSocket = factory.createSocket(this.mUrl);
this.mWebSocket.addListener(this.mWebSocketListener);
}
WebSocketThread.currentThreads.put(this.getId(),this); WebSocketThread.currentThreads.put(this.getId(),this);
mWebSocket.connect(); mWebSocket.connect();
} catch (WebSocketException e) {
} catch (final Exception e) {
Log.e(TAG, "WebSocketException. Msg: "+e.getMessage()); Log.e(TAG, "WebSocketException. Msg: "+e.getMessage());
} catch(NullPointerException e){
Log.e(TAG, "NullPointerException. Msg: "+e.getMessage());
} }
WebSocketThread.currentThreads.remove(this.getId()); WebSocketThread.currentThreads.remove(this.getId());
} }
@ -154,9 +127,4 @@ public class WebSocketThread extends Thread {
public boolean isConnected(){ public boolean isConnected(){
return mWebSocket.isOpen(); return mWebSocket.isOpen();
} }
public void setmUrl(String mUrl) {
this.mUrl = mUrl;
}
} }