Files
FairEmail/app/src/main/java/eu/faircode/email/ActivityBilling.java

271 lines
11 KiB
Java
Raw Normal View History

2018-09-04 18:51:09 +00:00
package eu.faircode.email;
2018-10-29 08:09:56 +00:00
/*
This file is part of FairEmail.
FairEmail is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-10-29 08:09:56 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-10-29 08:09:56 +00:00
2018-12-31 08:04:33 +00:00
Copyright 2018-2019 by Marcel Bokhorst (M66B)
2018-10-29 08:09:56 +00:00
*/
2018-09-04 18:51:09 +00:00
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
2018-12-16 15:08:50 +01:00
import android.util.Base64;
2019-01-10 09:37:13 +00:00
import android.view.View;
2018-09-04 18:51:09 +00:00
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.google.android.material.snackbar.Snackbar;
2018-12-16 15:08:50 +01:00
import java.security.KeyFactory;
2018-09-04 18:51:09 +00:00
import java.security.NoSuchAlgorithmException;
2018-12-16 15:08:50 +01:00
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
2018-09-04 18:51:09 +00:00
import java.util.List;
2018-11-17 10:36:11 +01:00
import androidx.annotation.Nullable;
2019-01-10 09:37:13 +00:00
import androidx.fragment.app.FragmentTransaction;
2018-12-15 09:12:12 +01:00
import androidx.lifecycle.Lifecycle;
2018-09-04 18:51:09 +00:00
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
abstract class ActivityBilling extends ActivityBase implements PurchasesUpdatedListener {
private BillingClient billingClient = null;
static final String ACTION_PURCHASE = BuildConfig.APPLICATION_ID + ".ACTION_PURCHASE";
static final String ACTION_ACTIVATE_PRO = BuildConfig.APPLICATION_ID + ".ACTIVATE_PRO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Helper.isPlayStoreInstall(this)) {
billingClient = BillingClient.newBuilder(this).setListener(this).build();
billingClient.startConnection(billingClientStateListener);
}
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
IntentFilter iff = new IntentFilter();
iff.addAction(ACTION_PURCHASE);
iff.addAction(ACTION_ACTIVATE_PRO);
lbm.registerReceiver(receiver, iff);
if (billingClient != null && billingClient.isReady())
queryPurchases();
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.unregisterReceiver(receiver);
}
@Override
protected void onDestroy() {
if (billingClient != null)
billingClient.endConnection();
super.onDestroy();
}
protected Intent getIntentPro() {
if (Helper.isPlayStoreInstall(this))
return null;
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
2019-01-13 15:29:29 +00:00
intent.setData(Uri.parse(BuildConfig.PRO_FEATURES + "?challenge=" + getChallenge()));
2018-09-04 18:51:09 +00:00
return intent;
} catch (NoSuchAlgorithmException ex) {
2018-12-24 12:27:45 +00:00
Log.e(ex);
2018-09-04 18:51:09 +00:00
return null;
}
}
private String getChallenge() throws NoSuchAlgorithmException {
String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
return Helper.sha256(android_id);
}
private String getResponse() throws NoSuchAlgorithmException {
return Helper.sha256(BuildConfig.APPLICATION_ID + getChallenge());
}
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_PURCHASE.equals(intent.getAction()))
onPurchase(intent);
else if (ACTION_ACTIVATE_PRO.equals(intent.getAction()))
onActivatePro(intent);
}
};
private void onPurchase(Intent intent) {
if (Helper.isPlayStoreInstall(this)) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku(BuildConfig.APPLICATION_ID + ".pro")
.setType(BillingClient.SkuType.INAPP)
.build();
int responseCode = billingClient.launchBillingFlow(this, flowParams);
String text = Helper.getBillingResponseText(responseCode);
2018-12-24 12:27:45 +00:00
Log.i("IAB launch billing flow response=" + text);
2018-09-04 18:51:09 +00:00
if (responseCode != BillingClient.BillingResponse.OK)
2018-12-07 18:44:20 +01:00
Snackbar.make(getVisibleView(), text, Snackbar.LENGTH_LONG).show();
2018-09-04 18:51:09 +00:00
} else
Helper.view(this, this, getIntentPro());
2018-09-04 18:51:09 +00:00
}
private void onActivatePro(Intent intent) {
try {
Uri data = intent.getParcelableExtra("uri");
String challenge = getChallenge();
String response = data.getQueryParameter("response");
2018-12-24 12:27:45 +00:00
Log.i("Challenge=" + challenge);
Log.i("Response=" + response);
2018-09-04 18:51:09 +00:00
String expected = getResponse();
if (expected.equals(response)) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("pro", true).apply();
2018-12-24 12:27:45 +00:00
Log.i("Response valid");
2019-01-10 09:37:13 +00:00
Snackbar snackbar = Snackbar.make(getVisibleView(), R.string.title_pro_valid, Snackbar.LENGTH_LONG);
snackbar.setAction(R.string.title_check, new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new FragmentPro()).addToBackStack("pro");
fragmentTransaction.commit();
}
});
snackbar.show();
2018-09-04 18:51:09 +00:00
} else {
2018-12-24 12:27:45 +00:00
Log.i("Response invalid");
2018-12-07 18:44:20 +01:00
Snackbar.make(getVisibleView(), R.string.title_pro_invalid, Snackbar.LENGTH_LONG).show();
2018-09-04 18:51:09 +00:00
}
} catch (NoSuchAlgorithmException ex) {
2018-12-24 12:27:45 +00:00
Log.e(ex);
Helper.unexpectedError(this, this, ex);
2018-09-04 18:51:09 +00:00
}
}
private BillingClientStateListener billingClientStateListener = new BillingClientStateListener() {
private int backoff = 4; // seconds
@Override
public void onBillingSetupFinished(@BillingClient.BillingResponse int responseCode) {
String text = Helper.getBillingResponseText(responseCode);
2018-12-24 12:27:45 +00:00
Log.i("IAB connected response=" + text);
2018-12-22 09:16:12 +01:00
if (!getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED))
return;
2018-09-04 18:51:09 +00:00
if (responseCode == BillingClient.BillingResponse.OK) {
backoff = 4;
queryPurchases();
} else
2018-12-07 18:44:20 +01:00
Snackbar.make(getVisibleView(), text, Snackbar.LENGTH_LONG).show();
2018-09-04 18:51:09 +00:00
}
@Override
public void onBillingServiceDisconnected() {
backoff *= 2;
2018-12-24 12:27:45 +00:00
Log.i("IAB disconnected retry in " + backoff + " s");
2018-09-04 18:51:09 +00:00
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
2018-12-22 09:16:12 +01:00
if (!billingClient.isReady())
2018-09-04 18:51:09 +00:00
billingClient.startConnection(billingClientStateListener);
}
}, backoff * 1000L);
}
};
@Override
2018-11-17 10:36:11 +01:00
public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
2018-09-04 18:51:09 +00:00
String text = Helper.getBillingResponseText(responseCode);
2018-12-24 12:27:45 +00:00
Log.i("IAB purchases updated response=" + text);
2019-01-22 10:19:49 +00:00
if (!getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED))
return;
2018-09-04 18:51:09 +00:00
if (responseCode == BillingClient.BillingResponse.OK)
checkPurchases(purchases);
else
2018-12-07 18:44:20 +01:00
Snackbar.make(getVisibleView(), text, Snackbar.LENGTH_LONG).show();
2018-09-04 18:51:09 +00:00
}
private void queryPurchases() {
Purchase.PurchasesResult result = billingClient.queryPurchases(BillingClient.SkuType.INAPP);
String text = Helper.getBillingResponseText(result.getResponseCode());
2018-12-24 12:27:45 +00:00
Log.i("IAB query purchases response=" + text);
2019-01-22 10:19:49 +00:00
2018-09-04 18:51:09 +00:00
if (result.getResponseCode() == BillingClient.BillingResponse.OK)
checkPurchases(result.getPurchasesList());
else
2018-12-07 18:44:20 +01:00
Snackbar.make(getVisibleView(), text, Snackbar.LENGTH_LONG).show();
2018-09-04 18:51:09 +00:00
}
private void checkPurchases(List<Purchase> purchases) {
if (purchases != null) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
2018-12-16 15:08:50 +01:00
2018-09-09 06:09:59 +00:00
if (prefs.getBoolean("play_store", true))
editor.remove("pro");
2018-12-16 15:08:50 +01:00
for (Purchase purchase : purchases)
try {
2018-12-24 12:27:45 +00:00
Log.i("IAB SKU=" + purchase.getSku());
2018-12-16 15:08:50 +01:00
byte[] decodedKey = Base64.decode(getString(R.string.public_key), Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(publicKey);
sig.update(purchase.getOriginalJson().getBytes());
if (sig.verify(Base64.decode(purchase.getSignature(), Base64.DEFAULT))) {
if ((BuildConfig.APPLICATION_ID + ".pro").equals(purchase.getSku())) {
editor.putBoolean("pro", true);
2018-12-24 12:27:45 +00:00
Log.i("IAB pro features activated");
2018-12-16 15:08:50 +01:00
}
} else {
2018-12-24 12:27:45 +00:00
Log.w("Invalid signature");
2018-12-16 15:08:50 +01:00
Snackbar.make(getVisibleView(), R.string.title_pro_invalid, Snackbar.LENGTH_LONG).show();
}
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.e(ex);
2018-12-16 15:08:50 +01:00
Snackbar.make(getVisibleView(), ex.getMessage(), Snackbar.LENGTH_LONG).show();
2018-09-04 18:51:09 +00:00
}
2018-12-16 15:08:50 +01:00
2018-09-04 18:51:09 +00:00
editor.apply();
}
}
}