parent
dab5e08910
commit
c23597066a
@ -1,159 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.layout;
|
||||
|
||||
import android.os.AsyncTask;
|
||||
import android.util.Log;
|
||||
|
||||
import com.m2049r.xmrwallet.util.Helper;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
public class AsyncExchangeRate extends AsyncTask<String, Void, Boolean> {
|
||||
static final String TAG = "AsyncExchangeRate";
|
||||
static final long TIME_REFRESH_INTERVAL = 60000; // refresh exchange rate max every minute
|
||||
|
||||
public interface Listener {
|
||||
void exchangeFailed();
|
||||
|
||||
// callback from AsyncExchangeRate when we have a rate
|
||||
void exchange(String currencyA, String currencyB, double rate);
|
||||
}
|
||||
|
||||
static long RateTime = 0;
|
||||
static double Rate = 0;
|
||||
static String Fiat = null;
|
||||
|
||||
private final WeakReference<Listener> exchangeViewRef;
|
||||
|
||||
public AsyncExchangeRate(Listener exchangeView) {
|
||||
super();
|
||||
exchangeViewRef = new WeakReference<>(exchangeView);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
super.onPreExecute();
|
||||
}
|
||||
|
||||
boolean inverse = false;
|
||||
String currencyA = null;
|
||||
String currencyB = null;
|
||||
|
||||
@Override
|
||||
protected Boolean doInBackground(String... params) {
|
||||
if (params.length != 2) return false;
|
||||
Log.d(TAG, "Getting " + params[0]);
|
||||
currencyA = params[0];
|
||||
currencyB = params[1];
|
||||
|
||||
String fiat = null;
|
||||
if (currencyA.equals("XMR")) {
|
||||
fiat = currencyB;
|
||||
inverse = false;
|
||||
}
|
||||
if (currencyB.equals("XMR")) {
|
||||
fiat = currencyA;
|
||||
inverse = true;
|
||||
}
|
||||
|
||||
if (currencyA.equals(currencyB)) {
|
||||
Fiat = null;
|
||||
Rate = 1;
|
||||
RateTime = System.currentTimeMillis();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (fiat == null) {
|
||||
Fiat = null;
|
||||
Rate = 0;
|
||||
RateTime = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!fiat.equals(Fiat)) { // new currency - reset all
|
||||
Fiat = fiat;
|
||||
Rate = 0;
|
||||
RateTime = 0;
|
||||
}
|
||||
|
||||
if (System.currentTimeMillis() > RateTime + TIME_REFRESH_INTERVAL) {
|
||||
Log.d(TAG, "Fetching " + Fiat);
|
||||
String closePrice = getExchangeRate(Fiat);
|
||||
if (closePrice != null) {
|
||||
try {
|
||||
Rate = Double.parseDouble(closePrice);
|
||||
RateTime = System.currentTimeMillis();
|
||||
return true;
|
||||
} catch (NumberFormatException ex) {
|
||||
Rate = 0;
|
||||
Log.e(TAG, ex.getLocalizedMessage());
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
Rate = 0;
|
||||
Log.e(TAG, "exchange url failed");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true; // no change but still valid
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(Boolean result) {
|
||||
super.onPostExecute(result);
|
||||
Listener exchangeView = exchangeViewRef.get();
|
||||
if (result) {
|
||||
Log.d(TAG, "yay! = " + Rate);
|
||||
if (exchangeView != null) {
|
||||
exchangeView.exchange(currencyA, currencyB, inverse ? (1 / Rate) : Rate);
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "nay!");
|
||||
if (exchangeView != null) {
|
||||
exchangeView.exchangeFailed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "https://api.kraken.com/0/public/Ticker?pair=XMREUR"
|
||||
String getExchangeRate(String fiat) {
|
||||
String jsonResponse =
|
||||
Helper.getUrl("https://api.kraken.com/0/public/Ticker?pair=XMR" + fiat);
|
||||
if (jsonResponse == null) return null;
|
||||
try {
|
||||
JSONObject response = new JSONObject(jsonResponse);
|
||||
JSONArray errors = response.getJSONArray("error");
|
||||
Log.e(TAG, "errors=" + errors.toString());
|
||||
if (errors.length() == 0) {
|
||||
JSONObject result = response.getJSONObject("result");
|
||||
JSONObject pair = result.getJSONObject("XXMRZ" + fiat);
|
||||
JSONArray close = pair.getJSONArray("c");
|
||||
String closePrice = close.getString(0);
|
||||
Log.d(TAG, "closePrice=" + closePrice);
|
||||
return closePrice;
|
||||
}
|
||||
} catch (JSONException ex) {
|
||||
Log.e(TAG, ex.getLocalizedMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (C) 2006 The Android Open Source Project
|
||||
* Copyright (c) 2017 m2049r
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.api;
|
||||
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
|
||||
public interface ExchangeApi {
|
||||
|
||||
/**
|
||||
* Queries the exchnage rate
|
||||
*
|
||||
* @param baseCurrency base currency
|
||||
* @param quoteCurrency quote currency
|
||||
* @param callback the callback with the exchange rate
|
||||
*/
|
||||
void queryExchangeRate(@NonNull final String baseCurrency, @NonNull final String quoteCurrency,
|
||||
@NonNull final ExchangeCallback callback);
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (C) 2006 The Android Open Source Project
|
||||
* Copyright (c) 2017 m2049r
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.api;
|
||||
|
||||
public interface ExchangeCallback {
|
||||
|
||||
void onSuccess(ExchangeRate exchangeRate);
|
||||
|
||||
void onError(Exception ex);
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.api;
|
||||
|
||||
public class ExchangeException extends Exception {
|
||||
private int code;
|
||||
private final String errorMsg;
|
||||
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
|
||||
public ExchangeException(final int code) {
|
||||
super();
|
||||
this.code = code;
|
||||
this.errorMsg = null;
|
||||
}
|
||||
|
||||
public ExchangeException(final String errorMsg) {
|
||||
super();
|
||||
this.code = 0;
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
public ExchangeException(final int code, final String errorMsg) {
|
||||
super();
|
||||
this.code = code;
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r et al.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.api;
|
||||
|
||||
public interface ExchangeRate {
|
||||
|
||||
String getServiceName();
|
||||
|
||||
String getBaseCurrency();
|
||||
|
||||
String getQuoteCurrency();
|
||||
|
||||
double getRate();
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r et al.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.kraken;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
interface ExchangeApiCall {
|
||||
|
||||
void call(@NonNull final String fiat, @NonNull final NetworkCallback callback);
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r et al.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.kraken;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.VisibleForTesting;
|
||||
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeApi;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeCallback;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeException;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
public class ExchangeApiImpl implements ExchangeApi, ExchangeApiCall {
|
||||
|
||||
@NonNull
|
||||
private final OkHttpClient okHttpClient;
|
||||
|
||||
private final HttpUrl baseUrl;
|
||||
|
||||
//so we can inject the mockserver url
|
||||
@VisibleForTesting
|
||||
ExchangeApiImpl(@NonNull final OkHttpClient okHttpClient, final HttpUrl baseUrl) {
|
||||
|
||||
this.okHttpClient = okHttpClient;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
public ExchangeApiImpl(@NonNull final OkHttpClient okHttpClient) {
|
||||
this(okHttpClient, HttpUrl.parse("https://api.kraken.com/0/public/Ticker"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queryExchangeRate(@NonNull final String baseCurrency, @NonNull final String quoteCurrency,
|
||||
@NonNull final ExchangeCallback callback) {
|
||||
ExchangeRateImpl.call(this, baseCurrency, quoteCurrency, callback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void call(@NonNull final String fiat, @NonNull final NetworkCallback callback) {
|
||||
|
||||
final HttpUrl url = baseUrl.newBuilder()
|
||||
.addQueryParameter("pair", "XMR" + fiat)
|
||||
.build();
|
||||
|
||||
final Request httpRequest = createHttpRequest(url);
|
||||
|
||||
okHttpClient.newCall(httpRequest).enqueue(new okhttp3.Callback() {
|
||||
@Override
|
||||
public void onFailure(final Call call, final IOException ex) {
|
||||
callback.onError(ex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(final Call call, final Response response) throws IOException {
|
||||
if (response.isSuccessful()) {
|
||||
try {
|
||||
final JSONObject json = new JSONObject(response.body().string());
|
||||
final JSONArray jsonError = json.getJSONArray("error");
|
||||
if (jsonError.length() > 0) {
|
||||
final String errorMsg = jsonError.getString(0);
|
||||
callback.onError(new ExchangeException(response.code(), errorMsg));
|
||||
} else {
|
||||
final JSONObject jsonResult = json.getJSONObject("result");
|
||||
callback.onSuccess(jsonResult);
|
||||
}
|
||||
} catch (JSONException ex) {
|
||||
callback.onError(new ExchangeException(ex.getLocalizedMessage()));
|
||||
}
|
||||
} else {
|
||||
callback.onError(new ExchangeException(response.code(), response.message()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Request createHttpRequest(final HttpUrl url) {
|
||||
return new Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r et al.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.kraken;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeCallback;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeException;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeRate;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
class ExchangeRateImpl implements ExchangeRate {
|
||||
|
||||
private final String baseCurrency;
|
||||
private final String quoteCurrency;
|
||||
private final double rate;
|
||||
|
||||
@Override
|
||||
public String getServiceName() {
|
||||
return "kraken.com";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseCurrency() {
|
||||
return baseCurrency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getQuoteCurrency() {
|
||||
return quoteCurrency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getRate() {
|
||||
return rate;
|
||||
}
|
||||
|
||||
ExchangeRateImpl(@NonNull final String baseCurrency, @NonNull final String quoteCurrency, double rate) {
|
||||
super();
|
||||
this.baseCurrency = baseCurrency;
|
||||
this.quoteCurrency = quoteCurrency;
|
||||
this.rate = rate;
|
||||
}
|
||||
|
||||
ExchangeRateImpl(final JSONObject jsonObject) throws JSONException, ExchangeException {
|
||||
try {
|
||||
final String key = jsonObject.keys().next(); // we expect only one
|
||||
Pattern pattern = Pattern.compile("^X(.*?)Z(.*?)$");
|
||||
Matcher matcher = pattern.matcher(key);
|
||||
if (matcher.find()) {
|
||||
this.baseCurrency = matcher.group(1);
|
||||
this.quoteCurrency = matcher.group(2);
|
||||
} else {
|
||||
throw new ExchangeException("no pair returned!");
|
||||
}
|
||||
|
||||
JSONObject pair = jsonObject.getJSONObject(key);
|
||||
JSONArray close = pair.getJSONArray("c");
|
||||
String closePrice = close.getString(0);
|
||||
if (closePrice != null) {
|
||||
try {
|
||||
this.rate = Double.parseDouble(closePrice);
|
||||
} catch (NumberFormatException ex) {
|
||||
throw new ExchangeException(ex.getLocalizedMessage());
|
||||
}
|
||||
} else {
|
||||
throw new ExchangeException("no close price returned!");
|
||||
}
|
||||
} catch (NoSuchElementException ex) {
|
||||
throw new ExchangeException(ex.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void call(@NonNull final ExchangeApiCall api,
|
||||
@NonNull final String baseCurrency, @NonNull final String quoteCurrency,
|
||||
@NonNull final ExchangeCallback callback) {
|
||||
|
||||
if (baseCurrency.equals(quoteCurrency)) {
|
||||
callback.onSuccess(new ExchangeRateImpl(baseCurrency, quoteCurrency, 1.0));
|
||||
return;
|
||||
}
|
||||
|
||||
boolean inverse = false;
|
||||
String fiat = null;
|
||||
|
||||
if (baseCurrency.equals("XMR")) {
|
||||
fiat = quoteCurrency;
|
||||
inverse = false;
|
||||
}
|
||||
|
||||
if (quoteCurrency.equals("XMR")) {
|
||||
fiat = baseCurrency;
|
||||
inverse = true;
|
||||
}
|
||||
|
||||
if (fiat == null) {
|
||||
callback.onError(new IllegalArgumentException("no fiat specified"));
|
||||
return;
|
||||
}
|
||||
|
||||
api.call(fiat, new NetworkCallback() {
|
||||
@Override
|
||||
public void onSuccess(JSONObject jsonObject) {
|
||||
try {
|
||||
final ExchangeRate exchangeRate = new ExchangeRateImpl(jsonObject);
|
||||
callback.onSuccess(exchangeRate);
|
||||
} catch (JSONException ex) {
|
||||
callback.onError(new ExchangeException(ex.getLocalizedMessage()));
|
||||
} catch (ExchangeException ex) {
|
||||
callback.onError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception ex) {
|
||||
callback.onError(ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r et al.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.kraken;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
interface NetworkCallback {
|
||||
|
||||
void onSuccess(JSONObject jsonObject);
|
||||
|
||||
void onError(Exception ex);
|
||||
|
||||
}
|
@ -1,151 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.util;
|
||||
|
||||
import android.os.AsyncTask;
|
||||
import android.util.Log;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class AsyncExchangeRate extends AsyncTask<String, Void, Boolean> {
|
||||
private static final String TAG = "AsyncGetExchangeRate";
|
||||
|
||||
private static final long TIME_REFRESH_INTERVAL = 60000; // refresh exchange rate max every minute
|
||||
|
||||
private static long RateTime = 0;
|
||||
private static double Rate = 0;
|
||||
private static String Fiat = null;
|
||||
|
||||
public interface Listener {
|
||||
void exchange(String currencyA, String currencyB, double rate);
|
||||
}
|
||||
|
||||
private Listener listener;
|
||||
|
||||
public AsyncExchangeRate(Listener listener) {
|
||||
super();
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
super.onPreExecute();
|
||||
}
|
||||
|
||||
private boolean inverse = false;
|
||||
private String currencyA = null;
|
||||
private String currencyB = null;
|
||||
|
||||
@Override
|
||||
protected Boolean doInBackground(String... params) {
|
||||
if (params.length != 2) return false;
|
||||
Log.d(TAG, "Getting " + params[0]);
|
||||
currencyA = params[0];
|
||||
currencyB = params[1];
|
||||
|
||||
String fiat = null;
|
||||
if (currencyA.equals("XMR")) {
|
||||
fiat = currencyB;
|
||||
inverse = false;
|
||||
}
|
||||
if (currencyB.equals("XMR")) {
|
||||
fiat = currencyA;
|
||||
inverse = true;
|
||||
}
|
||||
|
||||
if (currencyA.equals(currencyB)) {
|
||||
Fiat = null;
|
||||
Rate = 1;
|
||||
RateTime = System.currentTimeMillis();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (fiat == null) {
|
||||
Fiat = null;
|
||||
Rate = 0;
|
||||
RateTime = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!fiat.equals(Fiat)) { // new currency - reset all
|
||||
Fiat = fiat;
|
||||
Rate = 0;
|
||||
RateTime = 0;
|
||||
}
|
||||
|
||||
if (System.currentTimeMillis() > RateTime + TIME_REFRESH_INTERVAL) {
|
||||
Log.d(TAG, "Fetching " + Fiat);
|
||||
String closePrice = getExchangeRate(Fiat);
|
||||
if (closePrice != null) {
|
||||
try {
|
||||
Rate = Double.parseDouble(closePrice);
|
||||
RateTime = System.currentTimeMillis();
|
||||
return true;
|
||||
} catch (NumberFormatException ex) {
|
||||
Rate = 0;
|
||||
Log.e(TAG, ex.getLocalizedMessage());
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
Rate = 0;
|
||||
Log.e(TAG, "exchange url failed");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true; // no change but still valid
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(Boolean result) {
|
||||
super.onPostExecute(result);
|
||||
if (result) {
|
||||
Log.d(TAG, "yay! = " + Rate);
|
||||
if (listener != null) {
|
||||
listener.exchange(currencyA, currencyB, inverse ? (1 / Rate) : Rate);
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "nay!");
|
||||
}
|
||||
}
|
||||
|
||||
private String getExchangeRate(String fiat) {
|
||||
String jsonResponse =
|
||||
Helper.getUrl("https://api.kraken.com/0/public/Ticker?pair=XMR" + fiat);
|
||||
if (jsonResponse == null) return null;
|
||||
try {
|
||||
JSONObject response = new JSONObject(jsonResponse);
|
||||
JSONArray errors = response.getJSONArray("error");
|
||||
Log.e(TAG, "errors=" + errors.toString());
|
||||
if (errors.length() == 0) {
|
||||
JSONObject result = response.getJSONObject("result");
|
||||
JSONObject pair = result.getJSONObject("XXMRZ" + fiat);
|
||||
JSONArray close = pair.getJSONArray("c");
|
||||
String closePrice = close.getString(0);
|
||||
Log.d(TAG, "closePrice=" + closePrice);
|
||||
return closePrice;
|
||||
}
|
||||
} catch (JSONException ex) {
|
||||
Log.e(TAG, ex.getLocalizedMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// "https://api.kraken.com/0/public/Ticker?pair=XMREUR"
|
||||
}
|
@ -0,0 +1,186 @@
|
||||
/*
|
||||
* Copyright (c) 2017 m2049r et al.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.m2049r.xmrwallet.service.exchange.kraken;
|
||||
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeApi;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeCallback;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeException;
|
||||
import com.m2049r.xmrwallet.service.exchange.api.ExchangeRate;
|
||||
|
||||
import net.jodah.concurrentunit.Waiter;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.mockwebserver.MockResponse;
|
||||
import okhttp3.mockwebserver.MockWebServer;
|
||||
import okhttp3.mockwebserver.RecordedRequest;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class ExchangeRateTest {
|
||||
|
||||
private MockWebServer mockWebServer;
|
||||
|
||||
private ExchangeApi exchangeApi;
|
||||
|
||||
private final OkHttpClient okHttpClient = new OkHttpClient();
|
||||
private Waiter waiter;
|
||||
|
||||
@Mock
|
||||
ExchangeCallback mockExchangeCallback;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
mockWebServer = new MockWebServer();
|
||||
mockWebServer.start();
|
||||
|
||||
waiter = new Waiter();
|
||||
|
||||
MockitoAnnotations.initMocks(this);
|
||||
|
||||
exchangeApi = new ExchangeApiImpl(okHttpClient, mockWebServer.url("/"));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
mockWebServer.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryExchangeRate_shouldBeGetMethod()
|
||||
throws InterruptedException, TimeoutException {
|
||||
|
||||
exchangeApi.queryExchangeRate("XMR", "USD", mockExchangeCallback);
|
||||
|
||||
RecordedRequest request = mockWebServer.takeRequest();
|
||||
assertEquals("GET", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryExchangeRate_shouldHavePairInUrl()
|
||||
throws InterruptedException, TimeoutException {
|
||||
|
||||
exchangeApi.queryExchangeRate("XMR", "USD", mockExchangeCallback);
|
||||
|
||||
RecordedRequest request = mockWebServer.takeRequest();
|
||||
assertEquals("/?pair=XMRUSD", request.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryExchangeRate_wasSuccessfulShouldRespondWithRate()
|
||||
throws InterruptedException, JSONException, TimeoutException {
|
||||
final String base = "XMR";
|
||||
final String quote = "USD";
|
||||
final double rate = 100;
|
||||
MockResponse jsonMockResponse = new MockResponse().setBody(
|
||||
createMockExchangeRateResponse(base, quote, rate));
|
||||
mockWebServer.enqueue(jsonMockResponse);
|
||||
|
||||
exchangeApi.queryExchangeRate(base, quote, new ExchangeCallback() {
|
||||
@Override
|
||||
public void onSuccess(final ExchangeRate exchangeRate) {
|
||||
waiter.assertEquals(exchangeRate.getBaseCurrency(), base);
|
||||
waiter.assertEquals(exchangeRate.getQuoteCurrency(), quote);
|
||||
waiter.assertEquals(exchangeRate.getRate(), rate);
|
||||
waiter.resume();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final Exception e) {
|
||||
waiter.fail(e);
|
||||
waiter.resume();
|
||||
}
|
||||
});
|
||||
waiter.await();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryExchangeRate_wasNotSuccessfulShouldCallOnError()
|
||||
throws InterruptedException, JSONException, TimeoutException {
|
||||
mockWebServer.enqueue(new MockResponse().setResponseCode(500));
|
||||
exchangeApi.queryExchangeRate("XMR", "USD", new ExchangeCallback() {
|
||||
@Override
|
||||
public void onSuccess(final ExchangeRate exchangeRate) {
|
||||
waiter.fail();
|
||||
waiter.resume();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final Exception e) {
|
||||
waiter.assertTrue(e instanceof ExchangeException);
|
||||
waiter.assertTrue(((ExchangeException) e).getCode() == 500);
|
||||
waiter.resume();
|
||||
}
|
||||
|
||||
});
|
||||
waiter.await();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryExchangeRate_unknownAssetShouldCallOnError()
|
||||
throws InterruptedException, JSONException, TimeoutException {
|
||||
mockWebServer.enqueue(new MockResponse().
|
||||
setResponseCode(200).
|
||||
setBody("{\"error\":[\"EQuery:Unknown asset pair\"]}"));
|
||||
exchangeApi.queryExchangeRate("XMR", "ABC", new ExchangeCallback() {
|
||||
@Override
|
||||
public void onSuccess(final ExchangeRate exchangeRate) {
|
||||
waiter.fail();
|
||||
waiter.resume();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final Exception e) {
|
||||
waiter.assertTrue(e instanceof ExchangeException);
|
||||
ExchangeException ex = (ExchangeException) e;
|
||||
waiter.assertTrue(ex.getCode() == 200);
|
||||
waiter.assertEquals(ex.getErrorMsg(), "EQuery:Unknown asset pair");
|
||||
waiter.resume();
|
||||
}
|
||||
|
||||
});
|
||||
waiter.await();
|
||||
}
|
||||
|
||||
private String createMockExchangeRateResponse(final String base, final String quote, final double rate) {
|
||||
return "{\n" +
|
||||
" \"error\":[],\n" +
|
||||
" \"result\":{\n" +
|
||||
" \"X" + base + "Z" + quote + "\":{\n" +
|
||||
" \"a\":[\"" + rate + "\",\"322\",\"322.000\"],\n" +
|
||||
" \"b\":[\"" + rate + "\",\"76\",\"76.000\"],\n" +
|
||||
" \"c\":[\"" + rate + "\",\"2.90000000\"],\n" +
|
||||
" \"v\":[\"4559.03962053\",\"5231.33235586\"],\n" +
|
||||
" \"p\":[\"" + rate + "\",\"" + rate + "\"],\n" +
|
||||
" \"t\":[801,1014],\n" +
|
||||
" \"l\":[\"" + (rate * 0.8) + "\",\"" + rate + "\"],\n" +
|
||||
" \"h\":[\"" + (rate * 1.2) + "\",\"" + rate + "\"],\n" +
|
||||
" \"o\":\"" + rate + "\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
}
|
||||
}
|
Loading…
Reference in new issue