From 38796aeb892379b8c2b7e4e1d7af00c4c050e8dc Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 23 Nov 2017 11:34:52 +0100 Subject: Add Splash StartActivity * added Splash StartActivity to handle updates and initialization * created global Constants * renamed EIP Constants --- .../bitmaskclient/BaseConfigurationWizard.java | 8 +- .../main/java/se/leap/bitmaskclient/Constants.java | 6 ++ .../main/java/se/leap/bitmaskclient/Dashboard.java | 41 ++------ .../java/se/leap/bitmaskclient/LeapSRPSession.java | 3 - .../java/se/leap/bitmaskclient/OnBootReceiver.java | 7 +- .../se/leap/bitmaskclient/ProviderApiBase.java | 8 +- .../java/se/leap/bitmaskclient/StartActivity.java | 115 +++++++++++++++++++++ .../java/se/leap/bitmaskclient/VpnFragment.java | 33 +++--- .../java/se/leap/bitmaskclient/eip/Constants.java | 44 -------- .../main/java/se/leap/bitmaskclient/eip/EIP.java | 4 +- .../se/leap/bitmaskclient/eip/EIPConstants.java | 44 ++++++++ .../se/leap/bitmaskclient/eip/GatewaysManager.java | 4 +- .../se/leap/bitmaskclient/eip/VoidVpnLauncher.java | 2 +- .../se/leap/bitmaskclient/eip/VoidVpnService.java | 2 +- .../leap/bitmaskclient/eip/VpnConfigGenerator.java | 4 +- 15 files changed, 211 insertions(+), 114 deletions(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/Constants.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/StartActivity.java delete mode 100644 app/src/main/java/se/leap/bitmaskclient/eip/Constants.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 4f6163bc..5dae1227 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -51,7 +51,7 @@ import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnItemClick; -import se.leap.bitmaskclient.eip.Constants; +import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.userstatus.SessionDialog; import static android.view.View.GONE; @@ -134,7 +134,7 @@ public abstract class BaseConfigurationWizard extends Activity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - preferences = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); fragment_manager = new FragmentManagerEnhanced(getFragmentManager()); provider_manager = ProviderManager.getInstance(getAssets(), getExternalFilesDir(null)); @@ -220,7 +220,7 @@ public abstract class BaseConfigurationWizard extends Activity e.printStackTrace(); } - if (preferences.getBoolean(Constants.ALLOWED_ANON, false)) { + if (preferences.getBoolean(EIPConstants.ALLOWED_ANON, false)) { mConfigState.putExtra(SERVICES_RETRIEVED, true); downloadVpnCertificate(); @@ -297,7 +297,7 @@ public abstract class BaseConfigurationWizard extends Activity public void cancelSettingUpProvider() { mConfigState.setAction(PROVIDER_NOT_SET); adapter.showAllProviders(); - preferences.edit().remove(Provider.KEY).remove(Constants.ALLOWED_ANON).remove(Constants.KEY).apply(); + preferences.edit().remove(Provider.KEY).remove(EIPConstants.ALLOWED_ANON).remove(EIPConstants.KEY).apply(); } private void askDashboardToQuitApp() { diff --git a/app/src/main/java/se/leap/bitmaskclient/Constants.java b/app/src/main/java/se/leap/bitmaskclient/Constants.java new file mode 100644 index 00000000..4ce09892 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/Constants.java @@ -0,0 +1,6 @@ +package se.leap.bitmaskclient; + +public interface Constants { + String SHARED_PREFERENCES = "LEAPPreferences"; + String PREFERENCES_APP_VERSION = "bitmask version"; +} diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 3f1663d0..e2366551 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -1,20 +1,4 @@ -/** - * Copyright (c) 2013 LEAP Encryption Access Project and contributers - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * 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 - * along with this program. If not, see . - */ -/** +/* * Copyright (c) 2013 LEAP Encryption Access Project and contributers * * This program is free software: you can redistribute it and/or modify @@ -57,8 +41,7 @@ import java.net.URL; import butterknife.ButterKnife; import butterknife.InjectView; -import de.blinkt.openvpn.core.VpnStatus; -import se.leap.bitmaskclient.eip.Constants; +import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; @@ -76,7 +59,6 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec protected static final int SWITCH_PROVIDER = 1; public static final String TAG = Dashboard.class.getSimpleName(); - public static final String SHARED_PREFERENCES = "LEAPPreferences"; public static final String ACTION_QUIT = "quit"; public static final String ACTION_ASK_TO_CANCEL_VPN = "ask to cancel vpn"; public static final String REQUEST_CODE = "request_code"; @@ -84,7 +66,6 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec public static final String START_ON_BOOT = "dashboard start on boot"; //FIXME: remove OR FIX ON_BOOT public static final String ON_BOOT = "dashboard on boot"; - public static final String APP_VERSION = "bitmask version"; private static Context app; protected static SharedPreferences preferences; @@ -102,18 +83,14 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); fragment_manager = new FragmentManagerEnhanced(getFragmentManager()); - ProviderAPICommand.initialize(this); providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), this); if (app == null) { app = this; - - VpnStatus.initLogCache(getApplicationContext().getCacheDir()); handleVersion(); - User.init(getString(R.string.default_username)); } boolean provider_exists = previousProviderExists(savedInstanceState); if (provider_exists) { @@ -154,7 +131,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec private boolean providerInSharedPreferences() { return preferences != null && - preferences.getBoolean(Constants.PROVIDER_CONFIGURED, false); + preferences.getBoolean(EIPConstants.PROVIDER_CONFIGURED, false); } @@ -179,13 +156,11 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec private void handleVersion() { try { int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; - int lastDetectedVersion = preferences.getInt(APP_VERSION, 0); - preferences.edit().putInt(APP_VERSION, versionCode).apply(); switch (versionCode) { case 91: // 0.6.0 without Bug #5999 case 101: // 0.8.0 - if (!preferences.getString(Constants.KEY, "").isEmpty()) + if (!preferences.getString(EIPConstants.KEY, "").isEmpty()) eip_fragment.updateEipService(); break; } @@ -230,7 +205,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec @SuppressLint("CommitPrefEdits") private void providerToPreferences(Provider provider) { - preferences.edit().putBoolean(Constants.PROVIDER_CONFIGURED, true).commit(); + preferences.edit().putBoolean(EIPConstants.PROVIDER_CONFIGURED, true).commit(); preferences.edit().putString(Provider.MAIN_URL, provider.mainUrl().toString()).apply(); preferences.edit().putString(Provider.KEY, provider.definition().toString()).apply(); } @@ -250,7 +225,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec .setNegativeButton(getResources().getString(R.string.setup_error_close_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - preferences.edit().remove(Provider.KEY).remove(Constants.PROVIDER_CONFIGURED).apply(); + preferences.edit().remove(Provider.KEY).remove(EIPConstants.PROVIDER_CONFIGURED).apply(); finish(); } }) @@ -341,7 +316,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec public void downloadVpnCertificate() { boolean is_authenticated = User.loggedIn(); - boolean allowed_anon = preferences.getBoolean(Constants.ALLOWED_ANON, false); + boolean allowed_anon = preferences.getBoolean(EIPConstants.ALLOWED_ANON, false); if (allowed_anon || is_authenticated) ProviderAPICommand.execute(Bundle.EMPTY, ProviderAPI.DOWNLOAD_CERTIFICATE, providerAPI_result_receiver); else diff --git a/app/src/main/java/se/leap/bitmaskclient/LeapSRPSession.java b/app/src/main/java/se/leap/bitmaskclient/LeapSRPSession.java index 49cf3774..3a1fd6e0 100644 --- a/app/src/main/java/se/leap/bitmaskclient/LeapSRPSession.java +++ b/app/src/main/java/se/leap/bitmaskclient/LeapSRPSession.java @@ -72,7 +72,6 @@ public class LeapSRPSession { * * @param username, the user ID * @param password, the user clear text password - * @param params, the SRP parameters for the session */ public LeapSRPSession(String username, String password) { this(username, password, null); @@ -84,7 +83,6 @@ public class LeapSRPSession { * * @param username, the user ID * @param password, the user clear text password - * @param params, the SRP parameters for the session * @param abytes, the random exponent used in the A public key */ public LeapSRPSession(String username, String password, byte[] abytes) { @@ -187,7 +185,6 @@ public class LeapSRPSession { * * @param b1 the positive source to build first BigInteger * @param b2 the positive source to build second BigInteger - * @param length * @return */ public byte[] xor(byte[] b1, byte[] b2) { diff --git a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java index 9171e816..a72a8809 100644 --- a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java +++ b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java @@ -2,7 +2,8 @@ package se.leap.bitmaskclient; import android.content.*; -import se.leap.bitmaskclient.eip.*; +import se.leap.bitmaskclient.eip.EIPConstants; + public class OnBootReceiver extends BroadcastReceiver { @@ -11,12 +12,12 @@ public class OnBootReceiver extends BroadcastReceiver { // Debug: am broadcast -a android.intent.action.BOOT_COMPLETED @Override public void onReceive(Context context, Intent intent) { - preferences = context.getSharedPreferences(Dashboard.SHARED_PREFERENCES, Context.MODE_PRIVATE); + preferences = context.getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); boolean provider_configured = !preferences.getString(Provider.KEY, "").isEmpty(); boolean start_on_boot = preferences.getBoolean(Dashboard.START_ON_BOOT, false); if (provider_configured && start_on_boot) { Intent dashboard_intent = new Intent(context, Dashboard.class); - dashboard_intent.setAction(Constants.ACTION_START_EIP); + dashboard_intent.setAction(EIPConstants.ACTION_START_EIP); dashboard_intent.putExtra(Dashboard.ON_BOOT, true); dashboard_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(dashboard_intent); diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java index acac607c..81852983 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java @@ -67,7 +67,7 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.TlsVersion; -import se.leap.bitmaskclient.eip.Constants; +import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatus; @@ -151,7 +151,7 @@ public abstract class ProviderApiBase extends IntentService { public void onCreate() { super.onCreate(); - preferences = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); resources = getResources(); } @@ -817,11 +817,11 @@ public abstract class ProviderApiBase extends IntentService { RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); + preferences.edit().putString(EIPConstants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); + preferences.edit().putString(EIPConstants.VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); return true; } catch (CertificateException e) { // TODO Auto-generated catch block diff --git a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java new file mode 100644 index 00000000..410daf7d --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java @@ -0,0 +1,115 @@ +package se.leap.bitmaskclient; + +import android.app.Activity; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.support.annotation.IntDef; +import android.support.annotation.Nullable; +import android.util.Log; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import de.blinkt.openvpn.core.VpnStatus; +import se.leap.bitmaskclient.userstatus.User; + +/** + * Activity shown at startup. Evaluates if App is started for the first time or has been upgraded + * and acts and calls another activity accordingly. + * + */ +public class StartActivity extends Activity { + public static final String TAG = Dashboard.class.getSimpleName(); + + @Retention(RetentionPolicy.SOURCE) + @IntDef({FIRST, NORMAL, UPGRADE, DOWNGRADE}) + private @interface StartupMode {} + private static final int FIRST = 0; + private static final int NORMAL = 1; + private static final int UPGRADE = 2; + private static final int DOWNGRADE = 3; + + /** + * check if normal start, first run, up or downgrade + * @return @StartupMode + */ + @StartupMode + private int checkAppStart() { + SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + try { + int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + int lastDetectedVersion = preferences.getInt(Constants.PREFERENCES_APP_VERSION, -1); + + // versions do match -> normal start + if (versionCode == lastDetectedVersion) { + Log.d(TAG, "App start was: NORMAL START"); + return NORMAL; + } + + // something changed -> save current version + preferences.edit().putInt(Constants.PREFERENCES_APP_VERSION, versionCode).apply(); + + // no previous app version -> first start + if (lastDetectedVersion == -1 ) { + Log.d(TAG, "App start was: FIRST START"); + return FIRST; + } + + // version has increased -> upgrade + if (versionCode > lastDetectedVersion) { + Log.d(TAG, "App start was: UPGRADE"); + return UPGRADE; + } + // version has decreased -> downgrade + if (versionCode < lastDetectedVersion) { + Log.d(TAG, "App start was: DOWNGRADE"); + return DOWNGRADE; + } + + } catch (PackageManager.NameNotFoundException e) { + Log.d(TAG, "Splash screen didn't find any " + getPackageName() + " package"); + } + + return NORMAL; + } + + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent; + + Log.d(TAG, "Started"); + + switch (checkAppStart()) { + case NORMAL: + break; + + case FIRST: + // TODO start ProfileCreation & replace below code + intent = new Intent(this, Dashboard.class); + startActivity(intent); + break; + + case UPGRADE: + // TODO appropriate data copying + // TODO show donation dialog + break; + + case DOWNGRADE: + // TODO think how and why this should happen and what todo + break; + } + + // initialize app necessities + ProviderAPICommand.initialize(this); + VpnStatus.initLogCache(getApplicationContext().getCacheDir()); + User.init(getString(R.string.default_username)); + + // go to Dashboard + intent = new Intent(this, Dashboard.class); + startActivity(intent); + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index c85b0151..eff02193 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -33,7 +33,10 @@ import de.blinkt.openvpn.core.OpenVPNService; import de.blinkt.openvpn.core.ProfileManager; import de.blinkt.openvpn.core.VpnStatus; import mbanje.kurt.fabbutton.*; -import se.leap.bitmaskclient.eip.*; +import se.leap.bitmaskclient.eip.EIPConstants; +import se.leap.bitmaskclient.eip.EIP; +import se.leap.bitmaskclient.eip.EipStatus; +import se.leap.bitmaskclient.eip.VoidVpnService; public class VpnFragment extends Fragment implements Observer { @@ -112,7 +115,7 @@ public class VpnFragment extends Fragment implements Observer { public void onResume() { super.onResume(); //FIXME: avoid race conditions while checking certificate an logging in at about the same time - //eipCommand(Constants.ACTION_CHECK_CERT_VALIDITY); + //eipCommand(EIPConstants.ACTION_CHECK_CERT_VALIDITY); handleNewState(eip_status); bindOpenVpnService(); } @@ -161,13 +164,13 @@ public class VpnFragment extends Fragment implements Observer { } private boolean canStartEIP() { - boolean certificateExists = !Dashboard.preferences.getString(Constants.VPN_CERTIFICATE, "").isEmpty(); - boolean isAllowedAnon = Dashboard.preferences.getBoolean(Constants.ALLOWED_ANON, false); + boolean certificateExists = !Dashboard.preferences.getString(EIPConstants.VPN_CERTIFICATE, "").isEmpty(); + boolean isAllowedAnon = Dashboard.preferences.getBoolean(EIPConstants.ALLOWED_ANON, false); return (isAllowedAnon || certificateExists) && !eip_status.isConnected() && !eip_status.isConnecting(); } private boolean canLogInToStartEIP() { - boolean isAllowedRegistered = Dashboard.preferences.getBoolean(Constants.ALLOWED_REGISTERED, false); + boolean isAllowedRegistered = Dashboard.preferences.getBoolean(EIPConstants.ALLOWED_REGISTERED, false); boolean isLoggedIn = !LeapSRPSession.getToken().isEmpty(); return isAllowedRegistered && !isLoggedIn && !eip_status.isConnecting() && !eip_status.isConnected(); } @@ -204,7 +207,7 @@ public class VpnFragment extends Fragment implements Observer { eip_status.setConnecting(); saveStatus(); - eipCommand(Constants.ACTION_START_EIP); + eipCommand(EIPConstants.ACTION_START_EIP); } private void stop() { @@ -227,7 +230,7 @@ public class VpnFragment extends Fragment implements Observer { } protected void stopEipIfPossible() { - eipCommand(Constants.ACTION_STOP_EIP); + eipCommand(EIPConstants.ACTION_STOP_EIP); } private void downloadEIPServiceConfig() { @@ -255,7 +258,7 @@ public class VpnFragment extends Fragment implements Observer { } protected void updateEipService() { - eipCommand(Constants.ACTION_UPDATE_EIP_SERVICE); + eipCommand(EIPConstants.ACTION_UPDATE_EIP_SERVICE); } /** @@ -268,7 +271,7 @@ public class VpnFragment extends Fragment implements Observer { // TODO validate "action"...how do we get the list of intent-filters for a class via Android API? Intent vpn_intent = new Intent(dashboard.getApplicationContext(), EIP.class); vpn_intent.setAction(action); - vpn_intent.putExtra(Constants.RECEIVER_TAG, eip_receiver); + vpn_intent.putExtra(EIPConstants.RECEIVER_TAG, eip_receiver); dashboard.startService(vpn_intent); } @@ -341,9 +344,9 @@ public class VpnFragment extends Fragment implements Observer { protected void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); - String request = resultData.getString(Constants.REQUEST_TAG); + String request = resultData.getString(EIPConstants.REQUEST_TAG); - if (request.equals(Constants.ACTION_START_EIP)) { + if (request.equals(EIPConstants.ACTION_START_EIP)) { switch (resultCode) { case Activity.RESULT_OK: break; @@ -351,7 +354,7 @@ public class VpnFragment extends Fragment implements Observer { break; } - } else if (request.equals(Constants.ACTION_STOP_EIP)) { + } else if (request.equals(EIPConstants.ACTION_STOP_EIP)) { switch (resultCode) { case Activity.RESULT_OK: stop(); @@ -359,14 +362,14 @@ public class VpnFragment extends Fragment implements Observer { case Activity.RESULT_CANCELED: break; } - } else if (request.equals(Constants.EIP_NOTIFICATION)) { + } else if (request.equals(EIPConstants.EIP_NOTIFICATION)) { switch (resultCode) { case Activity.RESULT_OK: break; case Activity.RESULT_CANCELED: break; } - } else if (request.equals(Constants.ACTION_CHECK_CERT_VALIDITY)) { + } else if (request.equals(EIPConstants.ACTION_CHECK_CERT_VALIDITY)) { switch (resultCode) { case Activity.RESULT_OK: break; @@ -374,7 +377,7 @@ public class VpnFragment extends Fragment implements Observer { dashboard.downloadVpnCertificate(); break; } - } else if (request.equals(Constants.ACTION_UPDATE_EIP_SERVICE)) { + } else if (request.equals(EIPConstants.ACTION_UPDATE_EIP_SERVICE)) { switch (resultCode) { case Activity.RESULT_OK: if (wants_to_connect) diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/Constants.java b/app/src/main/java/se/leap/bitmaskclient/eip/Constants.java deleted file mode 100644 index db1cb4a1..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/eip/Constants.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2013 LEAP Encryption Access Project and contributers - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * 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 - * along with this program. If not, see . - */ -package se.leap.bitmaskclient.eip; - -/** - * Constants for intent passing, shared preferences - * - * @author Parménides GV - */ -public interface Constants { - - public final static String TAG = Constants.class.getSimpleName(); - - public final static String ACTION_CHECK_CERT_VALIDITY = TAG + ".CHECK_CERT_VALIDITY"; - public final static String ACTION_START_EIP = TAG + ".START_EIP"; - public final static String ACTION_STOP_EIP = TAG + ".STOP_EIP"; - public final static String ACTION_UPDATE_EIP_SERVICE = TAG + ".UPDATE_EIP_SERVICE"; - public final static String ACTION_IS_EIP_RUNNING = TAG + ".IS_RUNNING"; - public final static String EIP_NOTIFICATION = TAG + ".EIP_NOTIFICATION"; - public final static String ALLOWED_ANON = "allow_anonymous"; - public final static String ALLOWED_REGISTERED = "allow_registration"; - public final static String VPN_CERTIFICATE = "cert"; - public final static String PRIVATE_KEY = TAG + ".PRIVATE_KEY"; - public final static String KEY = TAG + ".KEY"; - public final static String RECEIVER_TAG = TAG + ".RECEIVER_TAG"; - public final static String REQUEST_TAG = TAG + ".REQUEST_TAG"; - public final static String START_BLOCKING_VPN_PROFILE = TAG + ".START_BLOCKING_VPN_PROFILE"; - public final static String PROVIDER_CONFIGURED = TAG + ".PROVIDER_CONFIGURED"; - -} diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java index 28a9bb50..8bbdf901 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java @@ -25,7 +25,7 @@ import org.json.*; import de.blinkt.openvpn.*; import se.leap.bitmaskclient.*; -import static se.leap.bitmaskclient.eip.Constants.*; +import static se.leap.bitmaskclient.eip.EIPConstants.*; /** * EIP is the abstract base class for interacting with and managing the Encrypted @@ -59,7 +59,7 @@ public final class EIP extends IntentService { super.onCreate(); context = getApplicationContext(); - preferences = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); eip_definition = eipDefinitionFromPreferences(); if (gateways_manager.isEmpty()) gatewaysFromPreferences(); diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java new file mode 100644 index 00000000..a56868f1 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2013 LEAP Encryption Access Project and contributers + * + * This program 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. + * + * This program is distributed in the hope that it will be useful, + * 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 + * along with this program. If not, see . + */ +package se.leap.bitmaskclient.eip; + +/** + * EIPConstants for intent passing, shared preferences + * + * @author Parménides GV + */ +public interface EIPConstants { + + String TAG = "Constants"; + + String ACTION_CHECK_CERT_VALIDITY = TAG + ".CHECK_CERT_VALIDITY"; + String ACTION_START_EIP = TAG + ".START_EIP"; + String ACTION_STOP_EIP = TAG + ".STOP_EIP"; + String ACTION_UPDATE_EIP_SERVICE = TAG + ".UPDATE_EIP_SERVICE"; + String ACTION_IS_EIP_RUNNING = TAG + ".IS_RUNNING"; + String EIP_NOTIFICATION = TAG + ".EIP_NOTIFICATION"; + String ALLOWED_ANON = "allow_anonymous"; + String ALLOWED_REGISTERED = "allow_registration"; + String VPN_CERTIFICATE = "cert"; + String PRIVATE_KEY = TAG + ".PRIVATE_KEY"; + String KEY = TAG + ".KEY"; + String RECEIVER_TAG = TAG + ".RECEIVER_TAG"; + String REQUEST_TAG = TAG + ".REQUEST_TAG"; + String START_BLOCKING_VPN_PROFILE = TAG + ".START_BLOCKING_VPN_PROFILE"; + String PROVIDER_CONFIGURED = TAG + ".PROVIDER_CONFIGURED"; + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java index 177f553e..25c99098 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java @@ -123,8 +123,8 @@ public class GatewaysManager { JSONObject result = new JSONObject(); try { result.put(Provider.CA_CERT, preferences.getString(Provider.CA_CERT, "")); - result.put(Constants.PRIVATE_KEY, preferences.getString(Constants.PRIVATE_KEY, "")); - result.put(Constants.VPN_CERTIFICATE, preferences.getString(Constants.VPN_CERTIFICATE, "")); + result.put(EIPConstants.PRIVATE_KEY, preferences.getString(EIPConstants.PRIVATE_KEY, "")); + result.put(EIPConstants.VPN_CERTIFICATE, preferences.getString(EIPConstants.VPN_CERTIFICATE, "")); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java index 5c9263b3..8ce8aa81 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java @@ -28,7 +28,7 @@ public class VoidVpnLauncher extends Activity { if (requestCode == VPN_USER_PERMISSION) { if (resultCode == RESULT_OK) { Intent void_vpn_service = new Intent(getApplicationContext(), VoidVpnService.class); - void_vpn_service.setAction(Constants.START_BLOCKING_VPN_PROFILE); + void_vpn_service.setAction(EIPConstants.START_BLOCKING_VPN_PROFILE); startService(void_vpn_service); } } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java index cbf0fed2..629b4304 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java @@ -16,7 +16,7 @@ public class VoidVpnService extends VpnService { @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : ""; - if (action == Constants.START_BLOCKING_VPN_PROFILE) { + if (action == EIPConstants.START_BLOCKING_VPN_PROFILE) { thread = new Thread(new Runnable() { public void run() { Builder builder = new Builder(); diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java index f428099e..33993139 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java @@ -118,14 +118,14 @@ public class VpnConfigGenerator { String key = "" + new_line - + secrets.getString(Constants.PRIVATE_KEY) + + secrets.getString(EIPConstants.PRIVATE_KEY) + new_line + ""; String openvpn_cert = "" + new_line - + secrets.getString(Constants.VPN_CERTIFICATE) + + secrets.getString(EIPConstants.VPN_CERTIFICATE) + new_line + ""; -- cgit v1.2.3 From da7293252f197e9b54c1abd8127b4abe45b95110 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Wed, 6 Dec 2017 01:58:21 +0100 Subject: move constants * move EIPConstants to Constants * unify EIPConstants where possible * create Updater --- .../bitmaskclient/BaseConfigurationWizard.java | 5 +- .../main/java/se/leap/bitmaskclient/Constants.java | 34 ++++++ .../main/java/se/leap/bitmaskclient/Dashboard.java | 11 +- .../java/se/leap/bitmaskclient/OnBootReceiver.java | 4 +- .../se/leap/bitmaskclient/ProviderApiBase.java | 5 +- .../java/se/leap/bitmaskclient/StartActivity.java | 116 +++++++++++++-------- .../se/leap/bitmaskclient/VersionMilestone.java | 6 ++ .../java/se/leap/bitmaskclient/VpnFragment.java | 31 +++--- .../main/java/se/leap/bitmaskclient/eip/EIP.java | 32 +++--- .../se/leap/bitmaskclient/eip/EIPConstants.java | 44 -------- .../se/leap/bitmaskclient/eip/GatewaysManager.java | 4 +- .../se/leap/bitmaskclient/eip/VoidVpnLauncher.java | 4 +- .../se/leap/bitmaskclient/eip/VoidVpnService.java | 4 +- .../leap/bitmaskclient/eip/VpnConfigGenerator.java | 4 +- .../bitmaskclient/updates/ConstantUnification.java | 18 ++++ 15 files changed, 178 insertions(+), 144 deletions(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java delete mode 100644 app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 5dae1227..2ff8a088 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -51,7 +51,6 @@ import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnItemClick; -import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.userstatus.SessionDialog; import static android.view.View.GONE; @@ -220,7 +219,7 @@ public abstract class BaseConfigurationWizard extends Activity e.printStackTrace(); } - if (preferences.getBoolean(EIPConstants.ALLOWED_ANON, false)) { + if (preferences.getBoolean(Constants.ALLOWED_ANON, false)) { mConfigState.putExtra(SERVICES_RETRIEVED, true); downloadVpnCertificate(); @@ -297,7 +296,7 @@ public abstract class BaseConfigurationWizard extends Activity public void cancelSettingUpProvider() { mConfigState.setAction(PROVIDER_NOT_SET); adapter.showAllProviders(); - preferences.edit().remove(Provider.KEY).remove(EIPConstants.ALLOWED_ANON).remove(EIPConstants.KEY).apply(); + preferences.edit().remove(Provider.KEY).remove(Constants.ALLOWED_ANON).remove(Constants.KEY).apply(); } private void askDashboardToQuitApp() { diff --git a/app/src/main/java/se/leap/bitmaskclient/Constants.java b/app/src/main/java/se/leap/bitmaskclient/Constants.java index 4ce09892..f330ef68 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Constants.java +++ b/app/src/main/java/se/leap/bitmaskclient/Constants.java @@ -1,6 +1,40 @@ package se.leap.bitmaskclient; public interface Constants { + + ////////////////////////////////////////////// + // PREFERENCES CONSTANTS + ///////////////////////////////////////////// + String SHARED_PREFERENCES = "LEAPPreferences"; String PREFERENCES_APP_VERSION = "bitmask version"; + + + ////////////////////////////////////////////// + // EIP CONSTANTS + ///////////////////////////////////////////// + + String EIP_ACTION_CHECK_CERT_VALIDITY = "EIP.CHECK_CERT_VALIDITY"; + String EIP_ACTION_START = "EIP.START"; + String EIP_ACTION_STOP = "EIP.STOP"; + String EIP_ACTION_UPDATE = "EIP.UPDATE"; + String EIP_ACTION_IS_RUNNING = "EIP.IS_RUNNING"; + String EIP_ACTION_BLOCK_VPN_PROFILE = "EIP.ACTION_BLOCK_VPN_PROFILE"; + + String EIP_NOTIFICATION = "EIP.NOTIFICATION"; + String EIP_RECEIVER = "EIP.RECEIVER"; + String EIP_REQUEST = "EIP.REQUEST"; + + + ////////////////////////////////////////////// + // ? CONSTANTS + ///////////////////////////////////////////// + + // TODO FIND BETTER NAMES AND DO NOT USE AS PREFERENCES KEY + String ALLOWED_ANON = "allow_anonymous"; + String ALLOWED_REGISTERED = "allow_registration"; + String VPN_CERTIFICATE = "cert"; + String PRIVATE_KEY = "Constants.PRIVATE_KEY"; + String KEY = "Constants.KEY"; + String PROVIDER_CONFIGURED = "Constants.PROVIDER_CONFIGURED"; } diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index e2366551..df558e08 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -41,7 +41,6 @@ import java.net.URL; import butterknife.ButterKnife; import butterknife.InjectView; -import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; @@ -131,7 +130,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec private boolean providerInSharedPreferences() { return preferences != null && - preferences.getBoolean(EIPConstants.PROVIDER_CONFIGURED, false); + preferences.getBoolean(Constants.PROVIDER_CONFIGURED, false); } @@ -160,7 +159,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec switch (versionCode) { case 91: // 0.6.0 without Bug #5999 case 101: // 0.8.0 - if (!preferences.getString(EIPConstants.KEY, "").isEmpty()) + if (!preferences.getString(Constants.KEY, "").isEmpty()) eip_fragment.updateEipService(); break; } @@ -205,7 +204,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec @SuppressLint("CommitPrefEdits") private void providerToPreferences(Provider provider) { - preferences.edit().putBoolean(EIPConstants.PROVIDER_CONFIGURED, true).commit(); + preferences.edit().putBoolean(Constants.PROVIDER_CONFIGURED, true).commit(); preferences.edit().putString(Provider.MAIN_URL, provider.mainUrl().toString()).apply(); preferences.edit().putString(Provider.KEY, provider.definition().toString()).apply(); } @@ -225,7 +224,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec .setNegativeButton(getResources().getString(R.string.setup_error_close_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - preferences.edit().remove(Provider.KEY).remove(EIPConstants.PROVIDER_CONFIGURED).apply(); + preferences.edit().remove(Provider.KEY).remove(Constants.PROVIDER_CONFIGURED).apply(); finish(); } }) @@ -316,7 +315,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec public void downloadVpnCertificate() { boolean is_authenticated = User.loggedIn(); - boolean allowed_anon = preferences.getBoolean(EIPConstants.ALLOWED_ANON, false); + boolean allowed_anon = preferences.getBoolean(Constants.ALLOWED_ANON, false); if (allowed_anon || is_authenticated) ProviderAPICommand.execute(Bundle.EMPTY, ProviderAPI.DOWNLOAD_CERTIFICATE, providerAPI_result_receiver); else diff --git a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java index a72a8809..9394e1b1 100644 --- a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java +++ b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java @@ -2,8 +2,6 @@ package se.leap.bitmaskclient; import android.content.*; -import se.leap.bitmaskclient.eip.EIPConstants; - public class OnBootReceiver extends BroadcastReceiver { @@ -17,7 +15,7 @@ public class OnBootReceiver extends BroadcastReceiver { boolean start_on_boot = preferences.getBoolean(Dashboard.START_ON_BOOT, false); if (provider_configured && start_on_boot) { Intent dashboard_intent = new Intent(context, Dashboard.class); - dashboard_intent.setAction(EIPConstants.ACTION_START_EIP); + dashboard_intent.setAction(Constants.EIP_ACTION_START); dashboard_intent.putExtra(Dashboard.ON_BOOT, true); dashboard_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(dashboard_intent); diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java index 81852983..b9063f18 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java @@ -67,7 +67,6 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.TlsVersion; -import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatus; @@ -817,11 +816,11 @@ public abstract class ProviderApiBase extends IntentService { RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(EIPConstants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); + preferences.edit().putString(Constants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(EIPConstants.VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); + preferences.edit().putString(Constants.VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); return true; } catch (CertificateException e) { // TODO Auto-generated catch block diff --git a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java index 410daf7d..ade43701 100644 --- a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java @@ -13,6 +13,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import de.blinkt.openvpn.core.VpnStatus; +import se.leap.bitmaskclient.updates.ConstantUnification; import se.leap.bitmaskclient.userstatus.User; /** @@ -31,40 +32,76 @@ public class StartActivity extends Activity { private static final int UPGRADE = 2; private static final int DOWNGRADE = 3; + private int versionCode; + private int previousVersionCode; + + private SharedPreferences preferences; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + + Log.d(TAG, "Started"); + + switch (checkAppStart()) { + case NORMAL: + break; + + case FIRST: + // TODO start ProfileCreation & replace below code + break; + + case UPGRADE: + executeUpgrade(); + // TODO show donation dialog + break; + + case DOWNGRADE: + // TODO think how and why this should happen and what todo + break; + } + + // initialize app necessities + ProviderAPICommand.initialize(this); + VpnStatus.initLogCache(getApplicationContext().getCacheDir()); + User.init(getString(R.string.default_username)); + + // go to Dashboard + Intent intent = new Intent(this, Dashboard.class); + startActivity(intent); + } + /** * check if normal start, first run, up or downgrade * @return @StartupMode */ @StartupMode private int checkAppStart() { - SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); try { - int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; - int lastDetectedVersion = preferences.getInt(Constants.PREFERENCES_APP_VERSION, -1); + versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + previousVersionCode = preferences.getInt(Constants.PREFERENCES_APP_VERSION, -1); // versions do match -> normal start - if (versionCode == lastDetectedVersion) { + if (versionCode == previousVersionCode) { Log.d(TAG, "App start was: NORMAL START"); return NORMAL; } - // something changed -> save current version - preferences.edit().putInt(Constants.PREFERENCES_APP_VERSION, versionCode).apply(); - // no previous app version -> first start - if (lastDetectedVersion == -1 ) { - Log.d(TAG, "App start was: FIRST START"); + if (previousVersionCode == -1 ) { + Log.d(TAG, "FIRST START"); return FIRST; } // version has increased -> upgrade - if (versionCode > lastDetectedVersion) { - Log.d(TAG, "App start was: UPGRADE"); + if (versionCode > previousVersionCode) { + Log.d(TAG, "UPGRADE"); return UPGRADE; } // version has decreased -> downgrade - if (versionCode < lastDetectedVersion) { - Log.d(TAG, "App start was: DOWNGRADE"); + if (versionCode < previousVersionCode) { + Log.d(TAG, "DOWNGRADE"); return DOWNGRADE; } @@ -75,41 +112,28 @@ public class StartActivity extends Activity { return NORMAL; } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Intent intent; - - Log.d(TAG, "Started"); - - switch (checkAppStart()) { - case NORMAL: - break; - - case FIRST: - // TODO start ProfileCreation & replace below code - intent = new Intent(this, Dashboard.class); - startActivity(intent); - break; - - case UPGRADE: - // TODO appropriate data copying - // TODO show donation dialog - break; - - case DOWNGRADE: - // TODO think how and why this should happen and what todo - break; + /** + * execute necessary updates for version change + */ + private void executeUpgrade() { + if (passedMilestone(VersionMilestone.MULTIPLE_PROFILES)) { + // TODO prepare usage of multiple profiles + } + if (passedMilestone(VersionMilestone.CONSTANT_UNIFICATION)) { + ConstantUnification.upgrade(preferences); } - // initialize app necessities - ProviderAPICommand.initialize(this); - VpnStatus.initLogCache(getApplicationContext().getCacheDir()); - User.init(getString(R.string.default_username)); + // ensure all upgrades have passed before storing new information + preferences.edit().putInt(Constants.PREFERENCES_APP_VERSION, versionCode).apply(); + } - // go to Dashboard - intent = new Intent(this, Dashboard.class); - startActivity(intent); + /** + * check if an upgrade passed or moved to given milestone + * @param milestone Version code of the Milestone VersionMilestone.MILE_STONE + * @return true if milestone is reached - false otherwise + */ + private boolean passedMilestone(int milestone) { + return previousVersionCode < milestone && versionCode >= milestone; } + } diff --git a/app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java b/app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java new file mode 100644 index 00000000..eac57d72 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java @@ -0,0 +1,6 @@ +package se.leap.bitmaskclient; + +public interface VersionMilestone { + int MULTIPLE_PROFILES = 132; + int CONSTANT_UNIFICATION = 132; +} diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index eff02193..7b01714f 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -32,11 +32,10 @@ import de.blinkt.openvpn.core.IOpenVPNServiceInternal; import de.blinkt.openvpn.core.OpenVPNService; import de.blinkt.openvpn.core.ProfileManager; import de.blinkt.openvpn.core.VpnStatus; -import mbanje.kurt.fabbutton.*; -import se.leap.bitmaskclient.eip.EIPConstants; import se.leap.bitmaskclient.eip.EIP; import se.leap.bitmaskclient.eip.EipStatus; import se.leap.bitmaskclient.eip.VoidVpnService; +import se.leap.bitmaskclient.userstatus.FabButton; public class VpnFragment extends Fragment implements Observer { @@ -115,7 +114,7 @@ public class VpnFragment extends Fragment implements Observer { public void onResume() { super.onResume(); //FIXME: avoid race conditions while checking certificate an logging in at about the same time - //eipCommand(EIPConstants.ACTION_CHECK_CERT_VALIDITY); + //eipCommand(Constants.EIP_ACTION_CHECK_CERT_VALIDITY); handleNewState(eip_status); bindOpenVpnService(); } @@ -164,13 +163,13 @@ public class VpnFragment extends Fragment implements Observer { } private boolean canStartEIP() { - boolean certificateExists = !Dashboard.preferences.getString(EIPConstants.VPN_CERTIFICATE, "").isEmpty(); - boolean isAllowedAnon = Dashboard.preferences.getBoolean(EIPConstants.ALLOWED_ANON, false); + boolean certificateExists = !Dashboard.preferences.getString(Constants.VPN_CERTIFICATE, "").isEmpty(); + boolean isAllowedAnon = Dashboard.preferences.getBoolean(Constants.ALLOWED_ANON, false); return (isAllowedAnon || certificateExists) && !eip_status.isConnected() && !eip_status.isConnecting(); } private boolean canLogInToStartEIP() { - boolean isAllowedRegistered = Dashboard.preferences.getBoolean(EIPConstants.ALLOWED_REGISTERED, false); + boolean isAllowedRegistered = Dashboard.preferences.getBoolean(Constants.ALLOWED_REGISTERED, false); boolean isLoggedIn = !LeapSRPSession.getToken().isEmpty(); return isAllowedRegistered && !isLoggedIn && !eip_status.isConnecting() && !eip_status.isConnected(); } @@ -207,7 +206,7 @@ public class VpnFragment extends Fragment implements Observer { eip_status.setConnecting(); saveStatus(); - eipCommand(EIPConstants.ACTION_START_EIP); + eipCommand(Constants.EIP_ACTION_START); } private void stop() { @@ -230,7 +229,7 @@ public class VpnFragment extends Fragment implements Observer { } protected void stopEipIfPossible() { - eipCommand(EIPConstants.ACTION_STOP_EIP); + eipCommand(Constants.EIP_ACTION_STOP); } private void downloadEIPServiceConfig() { @@ -258,7 +257,7 @@ public class VpnFragment extends Fragment implements Observer { } protected void updateEipService() { - eipCommand(EIPConstants.ACTION_UPDATE_EIP_SERVICE); + eipCommand(Constants.EIP_ACTION_UPDATE); } /** @@ -271,7 +270,7 @@ public class VpnFragment extends Fragment implements Observer { // TODO validate "action"...how do we get the list of intent-filters for a class via Android API? Intent vpn_intent = new Intent(dashboard.getApplicationContext(), EIP.class); vpn_intent.setAction(action); - vpn_intent.putExtra(EIPConstants.RECEIVER_TAG, eip_receiver); + vpn_intent.putExtra(Constants.EIP_RECEIVER, eip_receiver); dashboard.startService(vpn_intent); } @@ -344,9 +343,9 @@ public class VpnFragment extends Fragment implements Observer { protected void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); - String request = resultData.getString(EIPConstants.REQUEST_TAG); + String request = resultData.getString(Constants.EIP_REQUEST); - if (request.equals(EIPConstants.ACTION_START_EIP)) { + if (request.equals(Constants.EIP_ACTION_START)) { switch (resultCode) { case Activity.RESULT_OK: break; @@ -354,7 +353,7 @@ public class VpnFragment extends Fragment implements Observer { break; } - } else if (request.equals(EIPConstants.ACTION_STOP_EIP)) { + } else if (request.equals(Constants.EIP_ACTION_STOP)) { switch (resultCode) { case Activity.RESULT_OK: stop(); @@ -362,14 +361,14 @@ public class VpnFragment extends Fragment implements Observer { case Activity.RESULT_CANCELED: break; } - } else if (request.equals(EIPConstants.EIP_NOTIFICATION)) { + } else if (request.equals(Constants.EIP_NOTIFICATION)) { switch (resultCode) { case Activity.RESULT_OK: break; case Activity.RESULT_CANCELED: break; } - } else if (request.equals(EIPConstants.ACTION_CHECK_CERT_VALIDITY)) { + } else if (request.equals(Constants.EIP_ACTION_CHECK_CERT_VALIDITY)) { switch (resultCode) { case Activity.RESULT_OK: break; @@ -377,7 +376,7 @@ public class VpnFragment extends Fragment implements Observer { dashboard.downloadVpnCertificate(); break; } - } else if (request.equals(EIPConstants.ACTION_UPDATE_EIP_SERVICE)) { + } else if (request.equals(Constants.EIP_ACTION_UPDATE)) { switch (resultCode) { case Activity.RESULT_OK: if (wants_to_connect) diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java index 8bbdf901..929a0c70 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java @@ -25,8 +25,6 @@ import org.json.*; import de.blinkt.openvpn.*; import se.leap.bitmaskclient.*; -import static se.leap.bitmaskclient.eip.EIPConstants.*; - /** * EIP is the abstract base class for interacting with and managing the Encrypted * Internet Proxy connection. Connections are started, stopped, and queried through @@ -68,17 +66,17 @@ public final class EIP extends IntentService { @Override protected void onHandleIntent(Intent intent) { String action = intent.getAction(); - mReceiver = intent.getParcelableExtra(RECEIVER_TAG); + mReceiver = intent.getParcelableExtra(Constants.EIP_RECEIVER); - if (action.equals(ACTION_START_EIP)) + if (action.equals(Constants.EIP_ACTION_START)) startEIP(); - else if (action.equals(ACTION_STOP_EIP)) + else if (action.equals(Constants.EIP_ACTION_STOP)) stopEIP(); - else if (action.equals(ACTION_IS_EIP_RUNNING)) + else if (action.equals(Constants.EIP_ACTION_IS_RUNNING)) isRunning(); - else if (action.equals(ACTION_UPDATE_EIP_SERVICE)) + else if (action.equals(Constants.EIP_ACTION_UPDATE)) updateEIPService(); - else if (action.equals(ACTION_CHECK_CERT_VALIDITY)) + else if (action.equals(Constants.EIP_ACTION_CHECK_CERT_VALIDITY)) checkCertValidity(); } @@ -96,9 +94,9 @@ public final class EIP extends IntentService { if (gateway != null && gateway.getProfile() != null) { mReceiver = VpnFragment.getReceiver(); launchActiveGateway(); - tellToReceiver(ACTION_START_EIP, Activity.RESULT_OK); + tellToReceiver(Constants.EIP_ACTION_START, Activity.RESULT_OK); } else - tellToReceiver(ACTION_START_EIP, Activity.RESULT_CANCELED); + tellToReceiver(Constants.EIP_ACTION_START, Activity.RESULT_CANCELED); } /** @@ -126,7 +124,7 @@ public final class EIP extends IntentService { if (eip_status.isConnected() || eip_status.isConnecting()) result_code = Activity.RESULT_OK; - tellToReceiver(ACTION_STOP_EIP, result_code); + tellToReceiver(Constants.EIP_ACTION_STOP, result_code); } /** @@ -139,7 +137,7 @@ public final class EIP extends IntentService { int resultCode = (eip_status.isConnected()) ? Activity.RESULT_OK : Activity.RESULT_CANCELED; - tellToReceiver(ACTION_IS_EIP_RUNNING, resultCode); + tellToReceiver(Constants.EIP_ACTION_IS_RUNNING, resultCode); } /** @@ -150,13 +148,13 @@ public final class EIP extends IntentService { eip_definition = eipDefinitionFromPreferences(); if (eip_definition.length() > 0) updateGateways(); - tellToReceiver(ACTION_UPDATE_EIP_SERVICE, Activity.RESULT_OK); + tellToReceiver(Constants.EIP_ACTION_UPDATE, Activity.RESULT_OK); } private JSONObject eipDefinitionFromPreferences() { JSONObject result = new JSONObject(); try { - String eip_definition_string = preferences.getString(KEY, ""); + String eip_definition_string = preferences.getString(Constants.KEY, ""); if (!eip_definition_string.isEmpty()) { result = new JSONObject(eip_definition_string); } @@ -186,17 +184,17 @@ public final class EIP extends IntentService { } private void checkCertValidity() { - VpnCertificateValidator validator = new VpnCertificateValidator(preferences.getString(VPN_CERTIFICATE, "")); + VpnCertificateValidator validator = new VpnCertificateValidator(preferences.getString(Constants.VPN_CERTIFICATE, "")); int resultCode = validator.isValid() ? Activity.RESULT_OK : Activity.RESULT_CANCELED; - tellToReceiver(ACTION_CHECK_CERT_VALIDITY, resultCode); + tellToReceiver(Constants.EIP_ACTION_CHECK_CERT_VALIDITY, resultCode); } private void tellToReceiver(String action, int resultCode) { if (mReceiver != null) { Bundle resultData = new Bundle(); - resultData.putString(REQUEST_TAG, action); + resultData.putString(Constants.EIP_REQUEST, action); mReceiver.send(resultCode, resultData); } } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java deleted file mode 100644 index a56868f1..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIPConstants.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2013 LEAP Encryption Access Project and contributers - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * 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 - * along with this program. If not, see . - */ -package se.leap.bitmaskclient.eip; - -/** - * EIPConstants for intent passing, shared preferences - * - * @author Parménides GV - */ -public interface EIPConstants { - - String TAG = "Constants"; - - String ACTION_CHECK_CERT_VALIDITY = TAG + ".CHECK_CERT_VALIDITY"; - String ACTION_START_EIP = TAG + ".START_EIP"; - String ACTION_STOP_EIP = TAG + ".STOP_EIP"; - String ACTION_UPDATE_EIP_SERVICE = TAG + ".UPDATE_EIP_SERVICE"; - String ACTION_IS_EIP_RUNNING = TAG + ".IS_RUNNING"; - String EIP_NOTIFICATION = TAG + ".EIP_NOTIFICATION"; - String ALLOWED_ANON = "allow_anonymous"; - String ALLOWED_REGISTERED = "allow_registration"; - String VPN_CERTIFICATE = "cert"; - String PRIVATE_KEY = TAG + ".PRIVATE_KEY"; - String KEY = TAG + ".KEY"; - String RECEIVER_TAG = TAG + ".RECEIVER_TAG"; - String REQUEST_TAG = TAG + ".REQUEST_TAG"; - String START_BLOCKING_VPN_PROFILE = TAG + ".START_BLOCKING_VPN_PROFILE"; - String PROVIDER_CONFIGURED = TAG + ".PROVIDER_CONFIGURED"; - -} diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java index 25c99098..177f553e 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java @@ -123,8 +123,8 @@ public class GatewaysManager { JSONObject result = new JSONObject(); try { result.put(Provider.CA_CERT, preferences.getString(Provider.CA_CERT, "")); - result.put(EIPConstants.PRIVATE_KEY, preferences.getString(EIPConstants.PRIVATE_KEY, "")); - result.put(EIPConstants.VPN_CERTIFICATE, preferences.getString(EIPConstants.VPN_CERTIFICATE, "")); + result.put(Constants.PRIVATE_KEY, preferences.getString(Constants.PRIVATE_KEY, "")); + result.put(Constants.VPN_CERTIFICATE, preferences.getString(Constants.VPN_CERTIFICATE, "")); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java index 8ce8aa81..b1aab79c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnLauncher.java @@ -5,6 +5,8 @@ import android.content.*; import android.net.*; import android.os.*; +import se.leap.bitmaskclient.Constants; + public class VoidVpnLauncher extends Activity { private static final int VPN_USER_PERMISSION = 71; @@ -28,7 +30,7 @@ public class VoidVpnLauncher extends Activity { if (requestCode == VPN_USER_PERMISSION) { if (resultCode == RESULT_OK) { Intent void_vpn_service = new Intent(getApplicationContext(), VoidVpnService.class); - void_vpn_service.setAction(EIPConstants.START_BLOCKING_VPN_PROFILE); + void_vpn_service.setAction(Constants.EIP_ACTION_BLOCK_VPN_PROFILE); startService(void_vpn_service); } } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java index 629b4304..ff375553 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java @@ -6,6 +6,8 @@ import android.os.*; import java.io.*; +import se.leap.bitmaskclient.Constants; + public class VoidVpnService extends VpnService { static final String TAG = VoidVpnService.class.getSimpleName(); @@ -16,7 +18,7 @@ public class VoidVpnService extends VpnService { @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : ""; - if (action == EIPConstants.START_BLOCKING_VPN_PROFILE) { + if (action == Constants.EIP_ACTION_BLOCK_VPN_PROFILE) { thread = new Thread(new Runnable() { public void run() { Builder builder = new Builder(); diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java index 33993139..f428099e 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java @@ -118,14 +118,14 @@ public class VpnConfigGenerator { String key = "" + new_line - + secrets.getString(EIPConstants.PRIVATE_KEY) + + secrets.getString(Constants.PRIVATE_KEY) + new_line + ""; String openvpn_cert = "" + new_line - + secrets.getString(EIPConstants.VPN_CERTIFICATE) + + secrets.getString(Constants.VPN_CERTIFICATE) + new_line + ""; diff --git a/app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java b/app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java new file mode 100644 index 00000000..ba78fa00 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java @@ -0,0 +1,18 @@ +package se.leap.bitmaskclient.updates; + +import android.content.SharedPreferences; + +public class ConstantUnification { + + private String OLD_ALLOWED_ANON = "allow_anonymous"; + private String OLD_ALLOWED_REGISTERED = "allow_registration"; + private String OLD_VPN_CERTIFICATE = "cert"; + private String OLD_PRIVATE_KEY = "Constants.PRIVATE_KEY"; + private String OLD_KEY = "Constants.KEY"; + private String OLD_PROVIDER_CONFIGURED = "Constants.PROVIDER_CONFIGURED"; + + public static void upgrade(SharedPreferences preferences) { + // TODO MOVE SAVED DATA + } + +} -- cgit v1.2.3 From f8c2f76971f5a7f26d18e5e669d5e0ce9c560f3f Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 7 Dec 2017 12:52:29 +0100 Subject: Rename constants * renamed last constants * remove unnecessary updates/ConstantUnification --- .../se/leap/bitmaskclient/BaseConfigurationWizard.java | 4 ++-- app/src/main/java/se/leap/bitmaskclient/Constants.java | 14 ++++++-------- app/src/main/java/se/leap/bitmaskclient/Dashboard.java | 4 ++-- .../java/se/leap/bitmaskclient/FeatureVersionCode.java | 5 +++++ .../java/se/leap/bitmaskclient/ProviderApiBase.java | 6 +++--- .../main/java/se/leap/bitmaskclient/StartActivity.java | 14 +++++--------- .../java/se/leap/bitmaskclient/VersionMilestone.java | 6 ------ .../main/java/se/leap/bitmaskclient/VpnFragment.java | 6 +++--- app/src/main/java/se/leap/bitmaskclient/eip/EIP.java | 4 ++-- .../se/leap/bitmaskclient/eip/GatewaysManager.java | 5 +++-- .../se/leap/bitmaskclient/eip/VpnConfigGenerator.java | 4 ++-- .../bitmaskclient/updates/ConstantUnification.java | 18 ------------------ 12 files changed, 33 insertions(+), 57 deletions(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/FeatureVersionCode.java delete mode 100644 app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java delete mode 100644 app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 2ff8a088..21520dc4 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -219,7 +219,7 @@ public abstract class BaseConfigurationWizard extends Activity e.printStackTrace(); } - if (preferences.getBoolean(Constants.ALLOWED_ANON, false)) { + if (preferences.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, false)) { mConfigState.putExtra(SERVICES_RETRIEVED, true); downloadVpnCertificate(); @@ -296,7 +296,7 @@ public abstract class BaseConfigurationWizard extends Activity public void cancelSettingUpProvider() { mConfigState.setAction(PROVIDER_NOT_SET); adapter.showAllProviders(); - preferences.edit().remove(Provider.KEY).remove(Constants.ALLOWED_ANON).remove(Constants.KEY).apply(); + preferences.edit().remove(Provider.KEY).remove(Constants.PROVIDER_ALLOW_ANONYMOUS).remove(Constants.PROVIDER_KEY).apply(); } private void askDashboardToQuitApp() { diff --git a/app/src/main/java/se/leap/bitmaskclient/Constants.java b/app/src/main/java/se/leap/bitmaskclient/Constants.java index f330ef68..8723191c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Constants.java +++ b/app/src/main/java/se/leap/bitmaskclient/Constants.java @@ -27,14 +27,12 @@ public interface Constants { ////////////////////////////////////////////// - // ? CONSTANTS + // PROVIDER CONSTANTS ///////////////////////////////////////////// - - // TODO FIND BETTER NAMES AND DO NOT USE AS PREFERENCES KEY - String ALLOWED_ANON = "allow_anonymous"; - String ALLOWED_REGISTERED = "allow_registration"; - String VPN_CERTIFICATE = "cert"; - String PRIVATE_KEY = "Constants.PRIVATE_KEY"; - String KEY = "Constants.KEY"; + String PROVIDER_ALLOW_ANONYMOUS = "allow_anonymous"; + String PROVIDER_ALLOWED_REGISTERED = "allow_registration"; + String PROVIDER_VPN_CERTIFICATE = "cert"; + String PROVIDER_PRIVATE_KEY = "Constants.PROVIDER_PRIVATE_KEY"; + String PROVIDER_KEY = "Constants.PROVIDER_KEY"; String PROVIDER_CONFIGURED = "Constants.PROVIDER_CONFIGURED"; } diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index df558e08..1f0477c9 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -159,7 +159,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec switch (versionCode) { case 91: // 0.6.0 without Bug #5999 case 101: // 0.8.0 - if (!preferences.getString(Constants.KEY, "").isEmpty()) + if (!preferences.getString(Constants.PROVIDER_KEY, "").isEmpty()) eip_fragment.updateEipService(); break; } @@ -315,7 +315,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec public void downloadVpnCertificate() { boolean is_authenticated = User.loggedIn(); - boolean allowed_anon = preferences.getBoolean(Constants.ALLOWED_ANON, false); + boolean allowed_anon = preferences.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, false); if (allowed_anon || is_authenticated) ProviderAPICommand.execute(Bundle.EMPTY, ProviderAPI.DOWNLOAD_CERTIFICATE, providerAPI_result_receiver); else diff --git a/app/src/main/java/se/leap/bitmaskclient/FeatureVersionCode.java b/app/src/main/java/se/leap/bitmaskclient/FeatureVersionCode.java new file mode 100644 index 00000000..b2a39c1a --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/FeatureVersionCode.java @@ -0,0 +1,5 @@ +package se.leap.bitmaskclient; + +public interface FeatureVersionCode { + int MULTIPLE_PROFILES = 132; +} diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java index b9063f18..38981289 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java @@ -807,7 +807,7 @@ public abstract class ProviderApiBase extends IntentService { String certificateString = null, keyString = null; String[] certAndKey = cert_string.split("(?<=-\n)"); for (int i = 0; i < certAndKey.length - 1; i++) { - if (certAndKey[i].contains("KEY")) { + if (certAndKey[i].contains("PROVIDER_KEY")) { keyString = certAndKey[i++] + certAndKey[i]; } else if (certAndKey[i].contains("CERTIFICATE")) { certificateString = certAndKey[i++] + certAndKey[i]; @@ -816,11 +816,11 @@ public abstract class ProviderApiBase extends IntentService { RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); + preferences.edit().putString(Constants.PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE PROVIDER_KEY-----\n" + keyString + "-----END RSA PRIVATE PROVIDER_KEY-----").commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); + preferences.edit().putString(Constants.PROVIDER_VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); return true; } catch (CertificateException e) { // TODO Auto-generated catch block diff --git a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java index ade43701..dd2be212 100644 --- a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java @@ -13,7 +13,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import de.blinkt.openvpn.core.VpnStatus; -import se.leap.bitmaskclient.updates.ConstantUnification; import se.leap.bitmaskclient.userstatus.User; /** @@ -113,15 +112,12 @@ public class StartActivity extends Activity { } /** - * execute necessary updates for version change + * execute necessary upgrades for version change */ private void executeUpgrade() { - if (passedMilestone(VersionMilestone.MULTIPLE_PROFILES)) { + if (hasNewFeature(FeatureVersionCode.MULTIPLE_PROFILES)) { // TODO prepare usage of multiple profiles } - if (passedMilestone(VersionMilestone.CONSTANT_UNIFICATION)) { - ConstantUnification.upgrade(preferences); - } // ensure all upgrades have passed before storing new information preferences.edit().putInt(Constants.PREFERENCES_APP_VERSION, versionCode).apply(); @@ -129,11 +125,11 @@ public class StartActivity extends Activity { /** * check if an upgrade passed or moved to given milestone - * @param milestone Version code of the Milestone VersionMilestone.MILE_STONE + * @param featureVersionCode Version code of the Milestone FeatureVersionCode.MILE_STONE * @return true if milestone is reached - false otherwise */ - private boolean passedMilestone(int milestone) { - return previousVersionCode < milestone && versionCode >= milestone; + private boolean hasNewFeature(int featureVersionCode) { + return previousVersionCode < featureVersionCode && versionCode >= featureVersionCode; } } diff --git a/app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java b/app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java deleted file mode 100644 index eac57d72..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/VersionMilestone.java +++ /dev/null @@ -1,6 +0,0 @@ -package se.leap.bitmaskclient; - -public interface VersionMilestone { - int MULTIPLE_PROFILES = 132; - int CONSTANT_UNIFICATION = 132; -} diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index 7b01714f..f787a955 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -163,13 +163,13 @@ public class VpnFragment extends Fragment implements Observer { } private boolean canStartEIP() { - boolean certificateExists = !Dashboard.preferences.getString(Constants.VPN_CERTIFICATE, "").isEmpty(); - boolean isAllowedAnon = Dashboard.preferences.getBoolean(Constants.ALLOWED_ANON, false); + boolean certificateExists = !Dashboard.preferences.getString(Constants.PROVIDER_VPN_CERTIFICATE, "").isEmpty(); + boolean isAllowedAnon = Dashboard.preferences.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, false); return (isAllowedAnon || certificateExists) && !eip_status.isConnected() && !eip_status.isConnecting(); } private boolean canLogInToStartEIP() { - boolean isAllowedRegistered = Dashboard.preferences.getBoolean(Constants.ALLOWED_REGISTERED, false); + boolean isAllowedRegistered = Dashboard.preferences.getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, false); boolean isLoggedIn = !LeapSRPSession.getToken().isEmpty(); return isAllowedRegistered && !isLoggedIn && !eip_status.isConnecting() && !eip_status.isConnected(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java index 929a0c70..0b35dc3d 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java @@ -154,7 +154,7 @@ public final class EIP extends IntentService { private JSONObject eipDefinitionFromPreferences() { JSONObject result = new JSONObject(); try { - String eip_definition_string = preferences.getString(Constants.KEY, ""); + String eip_definition_string = preferences.getString(Constants.PROVIDER_KEY, ""); if (!eip_definition_string.isEmpty()) { result = new JSONObject(eip_definition_string); } @@ -184,7 +184,7 @@ public final class EIP extends IntentService { } private void checkCertValidity() { - VpnCertificateValidator validator = new VpnCertificateValidator(preferences.getString(Constants.VPN_CERTIFICATE, "")); + VpnCertificateValidator validator = new VpnCertificateValidator(preferences.getString(Constants.PROVIDER_VPN_CERTIFICATE, "")); int resultCode = validator.isValid() ? Activity.RESULT_OK : Activity.RESULT_CANCELED; diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java index 177f553e..43c16d00 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java @@ -36,6 +36,7 @@ import java.util.List; import de.blinkt.openvpn.VpnProfile; import de.blinkt.openvpn.core.Connection; import de.blinkt.openvpn.core.ProfileManager; +import se.leap.bitmaskclient.Constants; import se.leap.bitmaskclient.Provider; /** @@ -123,8 +124,8 @@ public class GatewaysManager { JSONObject result = new JSONObject(); try { result.put(Provider.CA_CERT, preferences.getString(Provider.CA_CERT, "")); - result.put(Constants.PRIVATE_KEY, preferences.getString(Constants.PRIVATE_KEY, "")); - result.put(Constants.VPN_CERTIFICATE, preferences.getString(Constants.VPN_CERTIFICATE, "")); + result.put(Constants.PROVIDER_PRIVATE_KEY, preferences.getString(Constants.PROVIDER_PRIVATE_KEY, "")); + result.put(Constants.PROVIDER_VPN_CERTIFICATE, preferences.getString(Constants.PROVIDER_VPN_CERTIFICATE, "")); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java index f428099e..54563ec4 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java @@ -118,14 +118,14 @@ public class VpnConfigGenerator { String key = "" + new_line - + secrets.getString(Constants.PRIVATE_KEY) + + secrets.getString(Constants.PROVIDER_PRIVATE_KEY) + new_line + ""; String openvpn_cert = "" + new_line - + secrets.getString(Constants.VPN_CERTIFICATE) + + secrets.getString(Constants.PROVIDER_VPN_CERTIFICATE) + new_line + ""; diff --git a/app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java b/app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java deleted file mode 100644 index ba78fa00..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/updates/ConstantUnification.java +++ /dev/null @@ -1,18 +0,0 @@ -package se.leap.bitmaskclient.updates; - -import android.content.SharedPreferences; - -public class ConstantUnification { - - private String OLD_ALLOWED_ANON = "allow_anonymous"; - private String OLD_ALLOWED_REGISTERED = "allow_registration"; - private String OLD_VPN_CERTIFICATE = "cert"; - private String OLD_PRIVATE_KEY = "Constants.PRIVATE_KEY"; - private String OLD_KEY = "Constants.KEY"; - private String OLD_PROVIDER_CONFIGURED = "Constants.PROVIDER_CONFIGURED"; - - public static void upgrade(SharedPreferences preferences) { - // TODO MOVE SAVED DATA - } - -} -- cgit v1.2.3 From b99938b1dc32f70800363f0faba88e7fd771abb4 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 7 Dec 2017 15:27:30 +0100 Subject: Undo renaming of KEY to PROVIDER_KEY * undo unwanted changes --- app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java index 38981289..6e3b8b08 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiBase.java @@ -807,7 +807,7 @@ public abstract class ProviderApiBase extends IntentService { String certificateString = null, keyString = null; String[] certAndKey = cert_string.split("(?<=-\n)"); for (int i = 0; i < certAndKey.length - 1; i++) { - if (certAndKey[i].contains("PROVIDER_KEY")) { + if (certAndKey[i].contains("KEY")) { keyString = certAndKey[i++] + certAndKey[i]; } else if (certAndKey[i].contains("CERTIFICATE")) { certificateString = certAndKey[i++] + certAndKey[i]; @@ -816,7 +816,7 @@ public abstract class ProviderApiBase extends IntentService { RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE PROVIDER_KEY-----\n" + keyString + "-----END RSA PRIVATE PROVIDER_KEY-----").commit(); + preferences.edit().putString(Constants.PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); -- cgit v1.2.3 From d835a9b8f38acf1970acc18ce2030f7d5f7377dd Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 28 Nov 2017 01:51:19 +0100 Subject: base for sidebar --- .../java/se/leap/bitmaskclient/MainActivity.java | 115 +++++++++ .../bitmaskclient/NavigationDrawerFragment.java | 282 +++++++++++++++++++++ .../java/se/leap/bitmaskclient/StartActivity.java | 2 +- 3 files changed, 398 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/MainActivity.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java new file mode 100644 index 00000000..d28d0784 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -0,0 +1,115 @@ +package se.leap.bitmaskclient; + + +import android.content.Context; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.support.v4.widget.DrawerLayout; + +public class MainActivity extends AppCompatActivity + implements NavigationDrawerFragment.NavigationDrawerCallbacks { + + /** + * Fragment managing the behaviors, interactions and presentation of the navigation drawer. + */ + private NavigationDrawerFragment mNavigationDrawerFragment; + + /** + * Used to store the last screen title. For use in {@link #restoreActionBar()}. + */ + private CharSequence mTitle; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); + + mNavigationDrawerFragment = (NavigationDrawerFragment) + getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); + mTitle = getTitle(); + + // Set up the drawer. + mNavigationDrawerFragment.setUp( + R.id.navigation_drawer, + (DrawerLayout) findViewById(R.id.drawer_layout)); + } + + @Override + public void onNavigationDrawerItemSelected(int position) { + // update the main content by replacing fragments + FragmentManager fragmentManager = getSupportFragmentManager(); + fragmentManager.beginTransaction() + .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) + .commit(); + } + + public void onSectionAttached(int number) { + switch (number) { + case 1: + mTitle = getString(R.string.title_section1); + break; + case 2: + mTitle = getString(R.string.title_section2); + break; + case 3: + mTitle = getString(R.string.title_section3); + break; + } + } + + public void restoreActionBar() { + ActionBar actionBar = getSupportActionBar(); + actionBar.setDisplayShowTitleEnabled(true); + actionBar.setTitle(mTitle); + } + + /** + * A placeholder fragment containing a simple view. + */ + public static class PlaceholderFragment extends Fragment { + /** + * The fragment argument representing the section number for this + * fragment. + */ + private static final String ARG_SECTION_NUMBER = "section_number"; + + public PlaceholderFragment() { + } + + /** + * Returns a new instance of this fragment for the given section + * number. + */ + public static PlaceholderFragment newInstance(int sectionNumber) { + PlaceholderFragment fragment = new PlaceholderFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_SECTION_NUMBER, sectionNumber); + fragment.setArguments(args); + return fragment; + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView = inflater.inflate(R.layout.fragment_main, container, false); + return rootView; + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + ((MainActivity) context).onSectionAttached( + getArguments().getInt(ARG_SECTION_NUMBER)); + } + } + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java new file mode 100644 index 00000000..22a4f8a0 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java @@ -0,0 +1,282 @@ +package se.leap.bitmaskclient; + + +import android.content.Context; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v4.app.Fragment; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; +import android.content.SharedPreferences; +import android.content.res.Configuration; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.Toast; + +/** + * Fragment used for managing interactions for and presentation of a navigation drawer. + * See the + * design guidelines for a complete explanation of the behaviors implemented here. + */ +public class NavigationDrawerFragment extends Fragment { + + /** + * Remember the position of the selected item. + */ + private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; + + /** + * Per the design guidelines, you should show the drawer on launch until the user manually + * expands it. This shared preference tracks this. + */ + private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; + + /** + * A pointer to the current callbacks instance (the Activity). + */ + private NavigationDrawerCallbacks mCallbacks; + + /** + * Helper component that ties the action bar to the navigation drawer. + */ + private ActionBarDrawerToggle mDrawerToggle; + + private DrawerLayout mDrawerLayout; + private View mDrawerView; + private ListView mDrawerListView; + private View mFragmentContainerView; + + private int mCurrentSelectedPosition = 0; + private boolean mFromSavedInstanceState; + private boolean mUserLearnedDrawer; + + public NavigationDrawerFragment() { + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Read in the flag indicating whether or not the user has demonstrated awareness of the + // drawer. See PREF_USER_LEARNED_DRAWER for details. + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); + mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); + + if (savedInstanceState != null) { + mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); + mFromSavedInstanceState = true; + } + + // Select either the default item (0) or the last selected item. + selectItem(mCurrentSelectedPosition); + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + // Indicate that this fragment would like to influence the set of actions in the action bar. + setHasOptionsMenu(true); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + mDrawerView = inflater.inflate(R.layout.drawer_main, container, false); + return mDrawerView; + } + + public boolean isDrawerOpen() { + return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); + } + + /** + * Users of this fragment must call this method to set up the navigation drawer interactions. + * + * @param fragmentId The android:id of this fragment in its activity's layout. + * @param drawerLayout The DrawerLayout containing this fragment's UI. + */ + public void setUp(int fragmentId, DrawerLayout drawerLayout) { + AppCompatActivity activity = (AppCompatActivity) getActivity(); + + mDrawerListView = mDrawerView.findViewById(R.id.accountList); + mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + selectItem(position); + } + }); + + ActionBar actionBar = activity.getSupportActionBar(); + mDrawerListView.setAdapter(new ArrayAdapter( + actionBar.getThemedContext(), + android.R.layout.simple_list_item_activated_1, + android.R.id.text1, + new String[]{ + getString(R.string.title_section1), + getString(R.string.title_section2), + getString(R.string.title_section3), + })); + mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); + mFragmentContainerView = activity.findViewById(fragmentId); + mDrawerLayout = drawerLayout; + + // set a custom shadow that overlays the main content when the drawer opens + mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + + actionBar.setDisplayHomeAsUpEnabled(true); + actionBar.setHomeButtonEnabled(true); + // ActionBarDrawerToggle ties together the the proper interactions + // between the navigation drawer and the action bar app icon. + mDrawerToggle = new ActionBarDrawerToggle( + getActivity(), + mDrawerLayout, + (Toolbar) drawerLayout.findViewById(R.id.toolbar), + R.string.navigation_drawer_open, + R.string.navigation_drawer_close + ) { + @Override + public void onDrawerClosed(View drawerView) { + super.onDrawerClosed(drawerView); + if (!isAdded()) { + return; + } + + getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() + } + + @Override + public void onDrawerOpened(View drawerView) { + super.onDrawerOpened(drawerView); + if (!isAdded()) { + return; + } + + if (!mUserLearnedDrawer) { + // The user manually opened the drawer; store this flag to prevent auto-showing + // the navigation drawer automatically in the future. + mUserLearnedDrawer = true; + SharedPreferences sp = PreferenceManager + .getDefaultSharedPreferences(getActivity()); + sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); + } + + getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() + } + }; + + // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, + // per the navigation drawer design guidelines. + if (!mUserLearnedDrawer && !mFromSavedInstanceState) { + mDrawerLayout.openDrawer(mFragmentContainerView); + } + + // Defer code dependent on restoration of previous instance state. + mDrawerLayout.post(new Runnable() { + @Override + public void run() { + mDrawerToggle.syncState(); + } + }); + + mDrawerLayout.addDrawerListener(mDrawerToggle); + } + + private void selectItem(int position) { + mCurrentSelectedPosition = position; + if (mDrawerListView != null) { + mDrawerListView.setItemChecked(position, true); + } + if (mDrawerLayout != null) { + mDrawerLayout.closeDrawer(mFragmentContainerView); + } + if (mCallbacks != null) { + mCallbacks.onNavigationDrawerItemSelected(position); + } + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + try { + mCallbacks = (NavigationDrawerCallbacks) context; + } catch (ClassCastException e) { + throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); + } + } + + @Override + public void onDetach() { + super.onDetach(); + mCallbacks = null; + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + // Forward the new configuration the drawer toggle component. + mDrawerToggle.onConfigurationChanged(newConfig); + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + if (mDrawerLayout != null && isDrawerOpen()) { + showGlobalContextActionBar(); + } + super.onCreateOptionsMenu(menu, inflater); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (mDrawerToggle.onOptionsItemSelected(item)) { + return true; + } + + if (item.getItemId() == R.id.action_example) { + Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show(); + return true; + } + + return super.onOptionsItemSelected(item); + } + + /** + * Per the navigation drawer design guidelines, updates the action bar to show the global app + * 'context', rather than just what's in the current screen. + */ + private void showGlobalContextActionBar() { + ActionBar actionBar = getActionBar(); + actionBar.setDisplayShowTitleEnabled(true); + actionBar.setTitle(R.string.app_name); + } + + private ActionBar getActionBar() { + return ((AppCompatActivity) getActivity()).getSupportActionBar(); + } + + /** + * Callbacks interface that all activities using this fragment must implement. + */ + public interface NavigationDrawerCallbacks { + /** + * Called when an item in the navigation drawer is selected. + */ + void onNavigationDrawerItemSelected(int position); + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java index dd2be212..1bf81aea 100644 --- a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java @@ -67,7 +67,7 @@ public class StartActivity extends Activity { User.init(getString(R.string.default_username)); // go to Dashboard - Intent intent = new Intent(this, Dashboard.class); + Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } -- cgit v1.2.3 From 08ec840de9657085d9a0baaab54f6b33e16a12d0 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 14 Dec 2017 21:21:22 +0100 Subject: add LogFragment --- .../java/se/leap/bitmaskclient/MainActivity.java | 44 +- .../bitmaskclient/NavigationDrawerFragment.java | 2 +- .../leap/bitmaskclient/fragments/LogFragment.java | 688 +++++++++++++++++++++ 3 files changed, 714 insertions(+), 20 deletions(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java index d28d0784..ceff8b20 100644 --- a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -13,6 +13,9 @@ import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; +import se.leap.bitmaskclient.fragments.LogFragment; + + public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks { @@ -47,41 +50,49 @@ public class MainActivity extends AppCompatActivity public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); + Fragment fragment; + switch (position) { + case 1: + case 2: + fragment = PlaceholderFragment.newInstance(); + break; + default: + fragment = new LogFragment(); + break; + } fragmentManager.beginTransaction() - .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) + .replace(R.id.container, fragment) .commit(); + onSectionAttached(position); } public void onSectionAttached(int number) { switch (number) { case 1: - mTitle = getString(R.string.title_section1); - break; - case 2: mTitle = getString(R.string.title_section2); break; - case 3: + case 2: mTitle = getString(R.string.title_section3); break; + default: + mTitle = getString(R.string.title_log_fragment); + break; } + restoreActionBar(); } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); - actionBar.setDisplayShowTitleEnabled(true); - actionBar.setTitle(mTitle); + if (actionBar != null) { + actionBar.setDisplayShowTitleEnabled(true); + actionBar.setSubtitle(mTitle); + } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { - /** - * The fragment argument representing the section number for this - * fragment. - */ - private static final String ARG_SECTION_NUMBER = "section_number"; - public PlaceholderFragment() { } @@ -89,11 +100,8 @@ public class MainActivity extends AppCompatActivity * Returns a new instance of this fragment for the given section * number. */ - public static PlaceholderFragment newInstance(int sectionNumber) { + public static PlaceholderFragment newInstance() { PlaceholderFragment fragment = new PlaceholderFragment(); - Bundle args = new Bundle(); - args.putInt(ARG_SECTION_NUMBER, sectionNumber); - fragment.setArguments(args); return fragment; } @@ -107,8 +115,6 @@ public class MainActivity extends AppCompatActivity @Override public void onAttach(Context context) { super.onAttach(context); - ((MainActivity) context).onSectionAttached( - getArguments().getInt(ARG_SECTION_NUMBER)); } } diff --git a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java index 22a4f8a0..a417b51a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java @@ -123,7 +123,7 @@ public class NavigationDrawerFragment extends Fragment { android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ - getString(R.string.title_section1), + getString(R.string.title_log_fragment), getString(R.string.title_section2), getString(R.string.title_section3), })); diff --git a/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java b/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java new file mode 100644 index 00000000..b72e53d5 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java @@ -0,0 +1,688 @@ +/* + * Copyright (c) 2012-2016 Arne Schwabe + * Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt + */ + +package se.leap.bitmaskclient.fragments; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ObjectAnimator; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.res.Resources; +import android.database.DataSetObserver; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.os.Handler; +import android.os.Handler.Callback; +import android.os.Message; +import android.preference.PreferenceManager; +import android.support.annotation.Nullable; +import android.support.v4.app.ListFragment; +import android.support.v7.app.AppCompatActivity; +import android.text.SpannableString; +import android.text.format.DateFormat; +import android.text.style.ImageSpan; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.LinearLayout; +import android.widget.ListAdapter; +import android.widget.ListView; +import android.widget.RadioGroup; +import android.widget.SeekBar; +import android.widget.TextView; +import android.widget.Toast; + +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; +import java.util.Locale; +import java.util.Vector; + +import de.blinkt.openvpn.LaunchVPN; +import de.blinkt.openvpn.VpnProfile; +import de.blinkt.openvpn.core.ConnectionStatus; +import de.blinkt.openvpn.core.LogItem; +import de.blinkt.openvpn.core.OpenVPNManagement; +import de.blinkt.openvpn.core.OpenVPNService; +import de.blinkt.openvpn.core.Preferences; +import de.blinkt.openvpn.core.ProfileManager; +import de.blinkt.openvpn.core.VpnStatus; +import de.blinkt.openvpn.core.VpnStatus.LogListener; +import de.blinkt.openvpn.core.VpnStatus.StateListener; +import se.leap.bitmaskclient.Dashboard; +import se.leap.bitmaskclient.NavigationDrawerFragment; +import se.leap.bitmaskclient.R; + +import static de.blinkt.openvpn.core.OpenVPNService.humanReadableByteCount; + +public class LogFragment extends ListFragment implements StateListener, SeekBar.OnSeekBarChangeListener, RadioGroup.OnCheckedChangeListener, VpnStatus.ByteCountListener { + private static final String LOGTIMEFORMAT = "logtimeformat"; + private static final int START_VPN_CONFIG = 0; + private static final String VERBOSITYLEVEL = "verbositylevel"; + + + + private SeekBar mLogLevelSlider; + private LinearLayout mOptionsLayout; + private RadioGroup mTimeRadioGroup; + private TextView mUpStatus; + private TextView mDownStatus; + private TextView mConnectStatus; + private boolean mShowOptionsLayout; + private CheckBox mClearLogCheckBox; + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + ladapter.setLogLevel(progress + 1); + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onCheckedChanged(RadioGroup group, int checkedId) { + switch (checkedId) { + case R.id.radioISO: + ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_ISO); + break; + case R.id.radioNone: + ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_NONE); + break; + case R.id.radioShort: + ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_SHORT); + break; + + } + } + + @Override + public void updateByteCount(long in, long out, long diffIn, long diffOut) { + //%2$s/s %1$s - ↑%4$s/s %3$s + Resources res = getActivity().getResources(); + final String down = String.format("%2$s %1$s", humanReadableByteCount(in, false, res), humanReadableByteCount(diffIn / OpenVPNManagement.mBytecountInterval, true, res)); + final String up = String.format("%2$s %1$s", humanReadableByteCount(out, false, res), humanReadableByteCount(diffOut / OpenVPNManagement.mBytecountInterval, true, res)); + + if (mUpStatus != null && mDownStatus != null) { + if (getActivity() != null) { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + mUpStatus.setText(up); + mDownStatus.setText(down); + } + }); + } + } + + } + + + class LogWindowListAdapter implements ListAdapter, LogListener, Callback { + + private static final int MESSAGE_NEWLOG = 0; + + private static final int MESSAGE_CLEARLOG = 1; + + private static final int MESSAGE_NEWTS = 2; + private static final int MESSAGE_NEWLOGLEVEL = 3; + + public static final int TIME_FORMAT_NONE = 0; + public static final int TIME_FORMAT_SHORT = 1; + public static final int TIME_FORMAT_ISO = 2; + private static final int MAX_STORED_LOG_ENTRIES = 1000; + + private Vector allEntries = new Vector<>(); + + private Vector currentLevelEntries = new Vector(); + + private Handler mHandler; + + private Vector observers = new Vector(); + + private int mTimeFormat = 0; + private int mLogLevel = 3; + + + public LogWindowListAdapter() { + initLogBuffer(); + if (mHandler == null) { + mHandler = new Handler(this); + } + + VpnStatus.addLogListener(this); + } + + + private void initLogBuffer() { + allEntries.clear(); + Collections.addAll(allEntries, VpnStatus.getlogbuffer()); + initCurrentMessages(); + } + + String getLogStr() { + String str = ""; + for (LogItem entry : allEntries) { + str += getTime(entry, TIME_FORMAT_ISO) + entry.getString(getActivity()) + '\n'; + } + return str; + } + + + private void shareLog() { + Intent shareIntent = new Intent(Intent.ACTION_SEND); + shareIntent.putExtra(Intent.EXTRA_TEXT, getLogStr()); + shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.ics_openvpn_log_file)); + shareIntent.setType("text/plain"); + startActivity(Intent.createChooser(shareIntent, "Send Logfile")); + } + + @Override + public void registerDataSetObserver(DataSetObserver observer) { + observers.add(observer); + + } + + @Override + public void unregisterDataSetObserver(DataSetObserver observer) { + observers.remove(observer); + } + + @Override + public int getCount() { + return currentLevelEntries.size(); + } + + @Override + public Object getItem(int position) { + return currentLevelEntries.get(position); + } + + @Override + public long getItemId(int position) { + return ((Object) currentLevelEntries.get(position)).hashCode(); + } + + @Override + public boolean hasStableIds() { + return true; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + TextView v; + if (convertView == null) + v = new TextView(getActivity()); + else + v = (TextView) convertView; + + LogItem le = currentLevelEntries.get(position); + String msg = le.getString(getActivity()); + String time = getTime(le, mTimeFormat); + msg = time + msg; + + int spanStart = time.length(); + + SpannableString t = new SpannableString(msg); + + //t.setSpan(getSpanImage(le,(int)v.getTextSize()),spanStart,spanStart+1, Spanned.SPAN_INCLUSIVE_INCLUSIVE); + v.setText(t); + return v; + } + + private String getTime(LogItem le, int time) { + if (time != TIME_FORMAT_NONE) { + Date d = new Date(le.getLogtime()); + java.text.DateFormat timeformat; + if (time == TIME_FORMAT_ISO) + timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); + else + timeformat = DateFormat.getTimeFormat(getActivity()); + + return timeformat.format(d) + " "; + + } else { + return ""; + } + + } + + private ImageSpan getSpanImage(LogItem li, int imageSize) { + int imageRes = android.R.drawable.ic_menu_call; + + switch (li.getLogLevel()) { + case ERROR: + imageRes = android.R.drawable.ic_notification_clear_all; + break; + case INFO: + imageRes = android.R.drawable.ic_menu_compass; + break; + case VERBOSE: + imageRes = android.R.drawable.ic_menu_info_details; + break; + case WARNING: + imageRes = android.R.drawable.ic_menu_camera; + break; + } + + Drawable d = getResources().getDrawable(imageRes); + + + //d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); + d.setBounds(0, 0, imageSize, imageSize); + ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM); + + return span; + } + + @Override + public int getItemViewType(int position) { + return 0; + } + + @Override + public int getViewTypeCount() { + return 1; + } + + @Override + public boolean isEmpty() { + return currentLevelEntries.isEmpty(); + + } + + @Override + public boolean areAllItemsEnabled() { + return true; + } + + @Override + public boolean isEnabled(int position) { + return true; + } + + @Override + public void newLog(LogItem logMessage) { + Message msg = Message.obtain(); + assert (msg != null); + msg.what = MESSAGE_NEWLOG; + Bundle bundle = new Bundle(); + bundle.putParcelable("logmessage", logMessage); + msg.setData(bundle); + mHandler.sendMessage(msg); + } + + @Override + public boolean handleMessage(Message msg) { + // We have been called + if (msg.what == MESSAGE_NEWLOG) { + + LogItem logMessage = msg.getData().getParcelable("logmessage"); + if (addLogMessage(logMessage)) + for (DataSetObserver observer : observers) { + observer.onChanged(); + } + } else if (msg.what == MESSAGE_CLEARLOG) { + for (DataSetObserver observer : observers) { + observer.onInvalidated(); + } + initLogBuffer(); + } else if (msg.what == MESSAGE_NEWTS) { + for (DataSetObserver observer : observers) { + observer.onInvalidated(); + } + } else if (msg.what == MESSAGE_NEWLOGLEVEL) { + initCurrentMessages(); + + for (DataSetObserver observer : observers) { + observer.onChanged(); + } + + } + + return true; + } + + private void initCurrentMessages() { + currentLevelEntries.clear(); + for (LogItem li : allEntries) { + if (li.getVerbosityLevel() <= mLogLevel || + mLogLevel == VpnProfile.MAXLOGLEVEL) + currentLevelEntries.add(li); + } + } + + /** + * @param logmessage + * @return True if the current entries have changed + */ + private boolean addLogMessage(LogItem logmessage) { + allEntries.add(logmessage); + + if (allEntries.size() > MAX_STORED_LOG_ENTRIES) { + Vector oldAllEntries = allEntries; + allEntries = new Vector(allEntries.size()); + for (int i = 50; i < oldAllEntries.size(); i++) { + allEntries.add(oldAllEntries.elementAt(i)); + } + initCurrentMessages(); + return true; + } else { + if (logmessage.getVerbosityLevel() <= mLogLevel) { + currentLevelEntries.add(logmessage); + return true; + } else { + return false; + } + } + } + + void clearLog() { + // Actually is probably called from GUI Thread as result of the user + // pressing a button. But better safe than sorry + VpnStatus.clearLog(); + VpnStatus.logInfo(R.string.logCleared); + mHandler.sendEmptyMessage(MESSAGE_CLEARLOG); + } + + + public void setTimeFormat(int newTimeFormat) { + mTimeFormat = newTimeFormat; + mHandler.sendEmptyMessage(MESSAGE_NEWTS); + } + + public void setLogLevel(int logLevel) { + mLogLevel = logLevel; + mHandler.sendEmptyMessage(MESSAGE_NEWLOGLEVEL); + } + + } + + + private LogWindowListAdapter ladapter; + private TextView mSpeedView; + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.clearlog) { + ladapter.clearLog(); + return true; + } else if (item.getItemId() == R.id.send) { + ladapter.shareLog(); + } else if (item.getItemId() == R.id.edit_vpn) { + VpnProfile lastConnectedprofile = ProfileManager.get(getActivity(), VpnStatus.getLastConnectedVPNProfile()); + + if (lastConnectedprofile != null) { + Intent vprefintent = new Intent(getActivity(), Dashboard.class) + .putExtra(VpnProfile.EXTRA_PROFILEUUID, lastConnectedprofile.getUUIDString()); + startActivityForResult(vprefintent, START_VPN_CONFIG); + } else { + Toast.makeText(getActivity(), R.string.log_no_last_vpn, Toast.LENGTH_LONG).show(); + } + } else if (item.getItemId() == R.id.toggle_time) { + showHideOptionsPanel(); + } else if (item.getItemId() == android.R.id.home) { + // This is called when the Home (Up) button is pressed + // in the Action Bar. + Intent parentActivityIntent = new Intent(getActivity(), Dashboard.class); + parentActivityIntent.addFlags( + Intent.FLAG_ACTIVITY_CLEAR_TOP | + Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(parentActivityIntent); + getActivity().finish(); + return true; + + } + return super.onOptionsItemSelected(item); + + } + + private void showHideOptionsPanel() { + boolean optionsVisible = (mOptionsLayout.getVisibility() != View.GONE); + + ObjectAnimator anim; + if (optionsVisible) { + anim = ObjectAnimator.ofFloat(mOptionsLayout, "alpha", 1.0f, 0f); + anim.addListener(collapseListener); + + } else { + mOptionsLayout.setVisibility(View.VISIBLE); + anim = ObjectAnimator.ofFloat(mOptionsLayout, "alpha", 0f, 1.0f); + //anim = new TranslateAnimation(0.0f, 0.0f, mOptionsLayout.getHeight(), 0.0f); + + } + + //anim.setInterpolator(new AccelerateInterpolator(1.0f)); + //anim.setDuration(300); + //mOptionsLayout.startAnimation(anim); + anim.start(); + + } + + AnimatorListenerAdapter collapseListener = new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animator) { + mOptionsLayout.setVisibility(View.GONE); + } + + }; + + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + inflater.inflate(R.menu.f_log, menu); + if (getResources().getBoolean(R.bool.logSildersAlwaysVisible)) + menu.removeItem(R.id.toggle_time); + } + + + @Override + public void onResume() { + super.onResume(); + Intent intent = new Intent(getActivity(), OpenVPNService.class); + intent.setAction(OpenVPNService.START_SERVICE); + } + + @Override + public void onStart() { + super.onStart(); + VpnStatus.addStateListener(this); + VpnStatus.addByteCountListener(this); + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == START_VPN_CONFIG && resultCode == Activity.RESULT_OK) { + String configuredVPN = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID); + + final VpnProfile profile = ProfileManager.get(getActivity(), configuredVPN); + ProfileManager.getInstance(getActivity()).saveProfile(getActivity(), profile); + // Name could be modified, reset List adapter + + AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); + dialog.setTitle(R.string.configuration_changed); + dialog.setMessage(R.string.restart_vpn_after_change); + + + dialog.setPositiveButton(R.string.restart, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Intent intent = new Intent(getActivity(), LaunchVPN.class); + intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUIDString()); + intent.setAction(Intent.ACTION_MAIN); + startActivity(intent); + } + + + }); + dialog.setNegativeButton(R.string.ignore, null); + dialog.create().show(); + } + super.onActivityResult(requestCode, resultCode, data); + } + + + @Override + public void onStop() { + super.onStop(); + VpnStatus.removeStateListener(this); + VpnStatus.removeByteCountListener(this); + + getActivity().getPreferences(0).edit().putInt(LOGTIMEFORMAT, ladapter.mTimeFormat) + .putInt(VERBOSITYLEVEL, ladapter.mLogLevel).apply(); + + } + + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + ListView lv = getListView(); + + lv.setOnItemLongClickListener(new OnItemLongClickListener() { + + @Override + public boolean onItemLongClick(AdapterView parent, View view, + int position, long id) { + ClipboardManager clipboard = (ClipboardManager) + getActivity().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("Log Entry", ((TextView) view).getText()); + clipboard.setPrimaryClip(clip); + Toast.makeText(getActivity(), R.string.copied_entry, Toast.LENGTH_SHORT).show(); + return true; + } + }); + } + + @Nullable + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.f_log, container, false); + + setHasOptionsMenu(true); + + ladapter = new LogWindowListAdapter(); + ladapter.mTimeFormat = getActivity().getPreferences(0).getInt(LOGTIMEFORMAT, 1); + int logLevel = getActivity().getPreferences(0).getInt(VERBOSITYLEVEL, 1); + ladapter.setLogLevel(logLevel); + + setListAdapter(ladapter); + + mTimeRadioGroup = (RadioGroup) v.findViewById(R.id.timeFormatRadioGroup); + mTimeRadioGroup.setOnCheckedChangeListener(this); + + if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_ISO) { + mTimeRadioGroup.check(R.id.radioISO); + } else if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_NONE) { + mTimeRadioGroup.check(R.id.radioNone); + } else if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_SHORT) { + mTimeRadioGroup.check(R.id.radioShort); + } + + mClearLogCheckBox = (CheckBox) v.findViewById(R.id.clearlogconnect); + mClearLogCheckBox.setChecked(PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(LaunchVPN.CLEARLOG, true)); + mClearLogCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + Preferences.getDefaultSharedPreferences(getActivity()).edit().putBoolean(LaunchVPN.CLEARLOG, isChecked).apply(); + } + }); + + mSpeedView = (TextView) v.findViewById(R.id.speed); + + mOptionsLayout = (LinearLayout) v.findViewById(R.id.logOptionsLayout); + mLogLevelSlider = (SeekBar) v.findViewById(R.id.LogLevelSlider); + mLogLevelSlider.setMax(VpnProfile.MAXLOGLEVEL - 1); + mLogLevelSlider.setProgress(logLevel - 1); + + mLogLevelSlider.setOnSeekBarChangeListener(this); + + if (getResources().getBoolean(R.bool.logSildersAlwaysVisible)) + mOptionsLayout.setVisibility(View.VISIBLE); + + mUpStatus = (TextView) v.findViewById(R.id.speedUp); + mDownStatus = (TextView) v.findViewById(R.id.speedDown); + mConnectStatus = (TextView) v.findViewById(R.id.speedStatus); + if (mShowOptionsLayout) + mOptionsLayout.setVisibility(View.VISIBLE); + return v; + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + // Scroll to the end of the list end + //getListView().setSelection(getListView().getAdapter().getCount()-1); + } + + @Override + public void onAttach(Context activity) { + super.onAttach(activity); + if (getResources().getBoolean(R.bool.logSildersAlwaysVisible)) { + mShowOptionsLayout = true; + if (mOptionsLayout != null) + mOptionsLayout.setVisibility(View.VISIBLE); + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + } + + + @Override + public void updateState(final String status, final String logMessage, final int resId, final ConnectionStatus level) { + if (isAdded()) { + final String cleanLogMessage = VpnStatus.getLastCleanLogMessage(getActivity()); + + getActivity().runOnUiThread(new Runnable() { + + @Override + public void run() { + if (isAdded()) { + if (mSpeedView != null) { + mSpeedView.setText(cleanLogMessage); + } + if (mConnectStatus != null) + mConnectStatus.setText(cleanLogMessage); + } + } + }); + } + } + + @Override + public void setConnectedVPN(String uuid) { + } + + + @Override + public void onDestroy() { + VpnStatus.removeLogListener(ladapter); + super.onDestroy(); + } + +} -- cgit v1.2.3 From f10380f7d8bc85d8127328a9d9c092bc109bb340 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 14 Dec 2017 21:41:46 +0100 Subject: add missing files --- app/src/main/java/se/leap/bitmaskclient/MainActivity.java | 2 +- app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java index ceff8b20..8cd6357c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -75,7 +75,7 @@ public class MainActivity extends AppCompatActivity mTitle = getString(R.string.title_section3); break; default: - mTitle = getString(R.string.title_log_fragment); + mTitle = getString(R.string.log_fragment_title); break; } restoreActionBar(); diff --git a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java index a417b51a..bb0d8f46 100644 --- a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java @@ -123,7 +123,7 @@ public class NavigationDrawerFragment extends Fragment { android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ - getString(R.string.title_log_fragment), + getString(R.string.log_fragment_title), getString(R.string.title_section2), getString(R.string.title_section3), })); -- cgit v1.2.3 From 7cd685e486e735c3994d59c01df98ac2f82dc0b2 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 19 Dec 2017 15:09:40 +0100 Subject: refactor dashboard --- .../bitmaskclient/BaseConfigurationWizard.java | 2 +- .../main/java/se/leap/bitmaskclient/Constants.java | 18 ++- .../main/java/se/leap/bitmaskclient/Dashboard.java | 140 ++++++++++--------- .../java/se/leap/bitmaskclient/OnBootReceiver.java | 2 +- .../java/se/leap/bitmaskclient/VpnFragment.java | 155 +++++++++++---------- .../main/java/se/leap/bitmaskclient/eip/EIP.java | 18 ++- .../bitmaskclient/eip/VpnCertificateValidator.java | 9 +- .../leap/bitmaskclient/eip/VpnConfigGenerator.java | 9 +- .../userstatus/UserStatusFragment.java | 17 +-- 9 files changed, 207 insertions(+), 163 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 21520dc4..52c8f8e5 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -301,7 +301,7 @@ public abstract class BaseConfigurationWizard extends Activity private void askDashboardToQuitApp() { Intent ask_quit = new Intent(); - ask_quit.putExtra(Dashboard.ACTION_QUIT, Dashboard.ACTION_QUIT); + ask_quit.putExtra(Constants.APP_ACTION_QUIT, Constants.APP_ACTION_QUIT); setResult(RESULT_CANCELED, ask_quit); } diff --git a/app/src/main/java/se/leap/bitmaskclient/Constants.java b/app/src/main/java/se/leap/bitmaskclient/Constants.java index a7ab56fd..7ee3adab 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Constants.java +++ b/app/src/main/java/se/leap/bitmaskclient/Constants.java @@ -10,6 +10,23 @@ public interface Constants { String PREFERENCES_APP_VERSION = "bitmask version"; + ////////////////////////////////////////////// + // REQUEST CODE CONSTANTS + ///////////////////////////////////////////// + + String REQUEST_CODE_KEY = "request_code"; + int REQUEST_CODE_CONFIGURE_LEAP = 0; + int REQUEST_CODE_SWITCH_PROVIDER = 1; + + + ////////////////////////////////////////////// + // APP CONSTANTS + ///////////////////////////////////////////// + + String APP_ACTION_QUIT = "quit"; + String APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE = "configure always-on profile"; + + ////////////////////////////////////////////// // EIP CONSTANTS ///////////////////////////////////////////// @@ -30,7 +47,6 @@ public interface Constants { String EIP_IS_ALWAYS_ON = "EIP.EIP_IS_ALWAYS_ON"; - ////////////////////////////////////////////// // PROVIDER CONSTANTS ///////////////////////////////////////////// diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index f1e7b3bd..1eed484c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -20,7 +20,6 @@ import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.FragmentTransaction; -import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; @@ -47,6 +46,8 @@ import se.leap.bitmaskclient.userstatus.UserStatusFragment; import static se.leap.bitmaskclient.Constants.EIP_IS_ALWAYS_ON; import static se.leap.bitmaskclient.Constants.EIP_RESTART_ON_BOOT; +import static se.leap.bitmaskclient.Constants.REQUEST_CODE_CONFIGURE_LEAP; +import static se.leap.bitmaskclient.Constants.REQUEST_CODE_SWITCH_PROVIDER; /** * The main user facing Activity of Bitmask Android, consisting of status, controls, @@ -55,13 +56,9 @@ import static se.leap.bitmaskclient.Constants.EIP_RESTART_ON_BOOT; * @author Sean Leonard * @author parmegv */ -public class Dashboard extends Activity implements ProviderAPIResultReceiver.Receiver { - - protected static final int CONFIGURE_LEAP = 0; - protected static final int SWITCH_PROVIDER = 1; +public class Dashboard extends Activity { public static final String TAG = Dashboard.class.getSimpleName(); - public static final String ACTION_QUIT = "quit"; /** * When "Disconnect" is clicked from the notification this extra gets added to the calling intent. @@ -69,39 +66,38 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec public static final String ACTION_ASK_TO_CANCEL_VPN = "ask to cancel vpn"; /** * if always-on feature is enabled, but there's no provider configured the EIP Service - * adds this intent extra. ACTION_CONFIGURE_ALWAYS_ON_PROFILE + * adds this intent extra. Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE * serves to start the Configuration Wizard on top of the Dashboard Activity. */ - public static final String ACTION_CONFIGURE_ALWAYS_ON_PROFILE = "configure always-on profile"; - public static final String REQUEST_CODE = "request_code"; - public static final String PARAMETERS = "dashboard parameters"; - public static final String APP_VERSION = "bitmask version"; - //FIXME: context classes in static fields lead to memory leaks! - private static Context dashboardContext; protected static SharedPreferences preferences; - private FragmentManagerEnhanced fragment_manager; + private static FragmentManagerEnhanced fragment_manager; @InjectView(R.id.providerName) TextView provider_name; - VpnFragment eip_fragment; - UserStatusFragment user_status_fragment; + private VpnFragment eip_fragment; + private UserStatusFragment user_status_fragment; + private static Provider provider = new Provider(); - public ProviderAPIResultReceiver providerAPI_result_receiver; - private boolean switching_provider; + public static ProviderAPIResultReceiver providerAPI_result_receiver; + private static boolean switching_provider; + private boolean handledVersion; + + public static DashboardReceiver dashboardReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + dashboardReceiver = new DashboardReceiver(this); preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); fragment_manager = new FragmentManagerEnhanced(getFragmentManager()); - providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), this); + providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), dashboardReceiver); - if (dashboardContext == null) { - dashboardContext = this; + if (handledVersion) { handleVersion(); + handledVersion = true; } prepareEIP(savedInstanceState); @@ -183,15 +179,15 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec } else if (intent.hasExtra(EIP_RESTART_ON_BOOT)) { Log.d(TAG, "Dashboard: EIP_RESTART_ON_BOOT"); prepareEIP(null); - } else if (intent.hasExtra(ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { - Log.d(TAG, "Dashboard: ACTION_CONFIGURE_ALWAYS_ON_PROFILE"); + } else if (intent.hasExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { + Log.d(TAG, "Dashboard: Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE"); handleConfigureAlwaysOn(getIntent()); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - if (requestCode == CONFIGURE_LEAP || requestCode == SWITCH_PROVIDER) { + if (requestCode == REQUEST_CODE_CONFIGURE_LEAP || requestCode == REQUEST_CODE_SWITCH_PROVIDER) { if (resultCode == RESULT_OK && data.hasExtra(Provider.KEY)) { provider = data.getParcelableExtra(Provider.KEY); providerToPreferences(provider); @@ -202,7 +198,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec sessionDialog(Bundle.EMPTY); } - } else if (resultCode == RESULT_CANCELED && data != null && data.hasExtra(ACTION_QUIT)) { + } else if (resultCode == RESULT_CANCELED && data != null && data.hasExtra(Constants.APP_ACTION_QUIT)) { finish(); } else configErrorDialog(); @@ -217,9 +213,9 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec } private void handleConfigureAlwaysOn(Intent intent) { - intent.removeExtra(ACTION_CONFIGURE_ALWAYS_ON_PROFILE); + intent.removeExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE); Log.d(TAG, "start Configuration wizard!"); - startActivityForResult(new Intent(this, ConfigurationWizard.class), CONFIGURE_LEAP); + startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_CONFIGURE_LEAP); } private void prepareEIP(Bundle savedInstanceState) { @@ -239,10 +235,10 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec } private void configureLeapProvider() { - if (getIntent().hasExtra(ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { - getIntent().removeExtra(ACTION_CONFIGURE_ALWAYS_ON_PROFILE); + if (getIntent().hasExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { + getIntent().removeExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE); } - startActivityForResult(new Intent(this, ConfigurationWizard.class), CONFIGURE_LEAP); + startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_CONFIGURE_LEAP); } @SuppressLint("CommitPrefEdits") private void providerToPreferences(Provider provider) { @@ -253,7 +249,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec } private void configErrorDialog() { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getContext()); + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setTitle(getResources().getString(R.string.setup_error_title)); alertBuilder .setMessage(getResources().getString(R.string.setup_error_text)) @@ -261,7 +257,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec .setPositiveButton(getResources().getString(R.string.setup_error_configure_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - startActivityForResult(new Intent(getContext(), ConfigurationWizard.class), CONFIGURE_LEAP); + startActivityForResult(new Intent(getApplicationContext(), ConfigurationWizard.class), Constants.REQUEST_CODE_CONFIGURE_LEAP); } }) .setNegativeButton(getResources().getString(R.string.setup_error_close_button), new DialogInterface.OnClickListener() { @@ -307,7 +303,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec * * @param hideAndTurnOnEipOnBoot Flag that indicates if system intent android.intent.action.BOOT_COMPLETED * has caused to start Dashboard - * @return + * @return the created VPNFragment */ private VpnFragment prepareEipFragment(boolean hideAndTurnOnEipOnBoot) { VpnFragment eip_fragment = new VpnFragment(); @@ -325,7 +321,7 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec /** * checks if Android's VPN feature 'always-on' is enabled for Bitmask - * @return + * @return true if 'always-on' is enabled false if not */ private boolean isAlwaysOn() { return preferences.getBoolean(EIP_IS_ALWAYS_ON, false); @@ -374,11 +370,13 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec } public void showLog() { - LogWindowWrapper log_window_wrapper = LogWindowWrapper.getInstance(getContext()); + LogWindowWrapper log_window_wrapper = LogWindowWrapper.getInstance(this); log_window_wrapper.showLog(); } - public void downloadVpnCertificate() { + + // TODO MOVE TO VPNManager(?) + public static void downloadVpnCertificate() { boolean is_authenticated = User.loggedIn(); boolean allowed_anon = preferences.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, false); if (allowed_anon || is_authenticated) @@ -387,7 +385,8 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec sessionDialog(Bundle.EMPTY); } - public void sessionDialog(Bundle resultData) { + // TODO how can we replace this + public static void sessionDialog(Bundle resultData) { try { FragmentTransaction transaction = fragment_manager.removePreviousFragment(SessionDialog.TAG); SessionDialog.getInstance(provider, resultData).show(transaction, SessionDialog.TAG); @@ -401,47 +400,52 @@ public class Dashboard extends Activity implements ProviderAPIResultReceiver.Rec preferences.edit().clear().apply(); switching_provider = false; - startActivityForResult(new Intent(this, ConfigurationWizard.class), SWITCH_PROVIDER); + startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); } - @Override - public void onReceiveResult(int resultCode, Bundle resultData) { - if (resultCode == ProviderAPI.SUCCESSFUL_SIGNUP) { - String username = resultData.getString(SessionDialog.USERNAME); - String password = resultData.getString(SessionDialog.PASSWORD); - user_status_fragment.logIn(username, password); - } else if (resultCode == ProviderAPI.FAILED_SIGNUP) { - sessionDialog(resultData); - } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGIN) { - downloadVpnCertificate(); - } else if (resultCode == ProviderAPI.FAILED_LOGIN) { - sessionDialog(resultData); - } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGOUT) { - if (switching_provider) switchProvider(); - } else if (resultCode == ProviderAPI.LOGOUT_FAILED) { - setResult(RESULT_CANCELED); - } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE) { - eip_fragment.updateEipService(); - setResult(RESULT_OK); - } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE) { - setResult(RESULT_CANCELED); - } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_EIP_SERVICE) { - eip_fragment.updateEipService(); - setResult(RESULT_OK); - } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_EIP_SERVICE) { - setResult(RESULT_CANCELED); + public static class DashboardReceiver implements ProviderAPIResultReceiver.Receiver{ + + private Dashboard dashboard; + + DashboardReceiver(Dashboard dashboard) { + this.dashboard = dashboard; } - } - public static Context getContext() { - return dashboardContext; + @Override + public void onReceiveResult(int resultCode, Bundle resultData) { + if (resultCode == ProviderAPI.SUCCESSFUL_SIGNUP) { + String username = resultData.getString(SessionDialog.USERNAME); + String password = resultData.getString(SessionDialog.PASSWORD); + dashboard.user_status_fragment.logIn(username, password); + } else if (resultCode == ProviderAPI.FAILED_SIGNUP) { + Dashboard.sessionDialog(resultData); + } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGIN) { + Dashboard.downloadVpnCertificate(); + } else if (resultCode == ProviderAPI.FAILED_LOGIN) { + Dashboard.sessionDialog(resultData); + } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGOUT) { + if (switching_provider) dashboard.switchProvider(); + } else if (resultCode == ProviderAPI.LOGOUT_FAILED) { + dashboard.setResult(RESULT_CANCELED); + } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE) { + dashboard.eip_fragment.updateEipService(); + dashboard.setResult(RESULT_OK); + } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE) { + dashboard.setResult(RESULT_CANCELED); + } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_EIP_SERVICE) { + dashboard.eip_fragment.updateEipService(); + dashboard.setResult(RESULT_OK); + } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_EIP_SERVICE) { + dashboard.setResult(RESULT_CANCELED); + } + } } public static Provider getProvider() { return provider; } @Override public void startActivityForResult(Intent intent, int requestCode) { - intent.putExtra(Dashboard.REQUEST_CODE, requestCode); + intent.putExtra(Constants.REQUEST_CODE_KEY, requestCode); super.startActivityForResult(intent, requestCode); } diff --git a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java index f9aa2660..a87e0460 100644 --- a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java +++ b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java @@ -41,7 +41,7 @@ public class OnBootReceiver extends BroadcastReceiver { } else { if (isAlwaysOnConfigured) { Intent dashboard_intent = new Intent(context, Dashboard.class); - dashboard_intent.putExtra(Dashboard.ACTION_CONFIGURE_ALWAYS_ON_PROFILE, true); + dashboard_intent.putExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE, true); dashboard_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(dashboard_intent); } diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index f1a15efd..2b968769 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -24,6 +24,7 @@ import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; +import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; @@ -72,12 +73,13 @@ public class VpnFragment extends Fragment implements Observer { protected static final String IS_CONNECTED = TAG + ".is_connected"; public static final String START_EIP_ON_BOOT = "start on boot"; + private SharedPreferences preferences; + @InjectView(R.id.vpn_status_image) FabButton vpn_status_image; @InjectView(R.id.vpn_main_button) Button main_button; - private Dashboard dashboard; private static EIPReceiver eip_receiver; private static EipStatus eip_status; private boolean wants_to_connect; @@ -104,8 +106,6 @@ public class VpnFragment extends Fragment implements Observer { //FIXME: replace with onAttach(Context context) public void onAttach(Activity activity) { super.onAttach(activity); - - dashboard = (Dashboard) activity; downloadEIPServiceConfig(); } @@ -115,6 +115,7 @@ public class VpnFragment extends Fragment implements Observer { eip_status = EipStatus.getInstance(); eip_status.addObserver(this); eip_receiver = new EIPReceiver(new Handler()); + preferences = getActivity().getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); } @Override @@ -142,7 +143,7 @@ public class VpnFragment extends Fragment implements Observer { @Override public void onPause() { super.onPause(); - dashboard.unbindService(openVpnConnection); + getActivity().unbindService(openVpnConnection); } @Override @@ -152,7 +153,7 @@ public class VpnFragment extends Fragment implements Observer { } private void saveStatus(boolean restartOnBoot) { - Dashboard.preferences.edit().putBoolean(EIP_RESTART_ON_BOOT, restartOnBoot).apply(); + preferences.edit().putBoolean(EIP_RESTART_ON_BOOT, restartOnBoot).apply(); } @OnClick(R.id.vpn_main_button) @@ -169,7 +170,7 @@ public class VpnFragment extends Fragment implements Observer { else if (canLogInToStartEIP()) { wants_to_connect = true; Bundle bundle = new Bundle(); - dashboard.sessionDialog(bundle); + Dashboard.sessionDialog(bundle); } else { Log.d(TAG, "WHAT IS GOING ON HERE?!"); // TODO: implement a fallback: check if vpncertificate was not downloaded properly or give @@ -178,13 +179,13 @@ public class VpnFragment extends Fragment implements Observer { } private boolean canStartEIP() { - boolean certificateExists = !Dashboard.preferences.getString(PROVIDER_VPN_CERTIFICATE, "").isEmpty(); - boolean isAllowedAnon = Dashboard.preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false); + boolean certificateExists = !preferences.getString(PROVIDER_VPN_CERTIFICATE, "").isEmpty(); + boolean isAllowedAnon = preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false); return (isAllowedAnon || certificateExists) && !eip_status.isConnected() && !eip_status.isConnecting(); } private boolean canLogInToStartEIP() { - boolean isAllowedRegistered = Dashboard.preferences.getBoolean(PROVIDER_ALLOWED_REGISTERED, false); + boolean isAllowedRegistered = preferences.getBoolean(PROVIDER_ALLOWED_REGISTERED, false); boolean isLoggedIn = !LeapSRPSession.getToken().isEmpty(); return isAllowedRegistered && !isLoggedIn && !eip_status.isConnecting() && !eip_status.isConnected(); } @@ -200,16 +201,17 @@ public class VpnFragment extends Fragment implements Observer { } private void askPendingStartCancellation() { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(dashboard); - alertBuilder.setTitle(dashboard.getString(R.string.eip_cancel_connect_title)) - .setMessage(dashboard.getString(R.string.eip_cancel_connect_text)) + Activity activity = getActivity(); + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity()); + alertBuilder.setTitle(activity.getString(R.string.eip_cancel_connect_title)) + .setMessage(activity.getString(R.string.eip_cancel_connect_text)) .setPositiveButton((android.R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { askToStopEIP(); } }) - .setNegativeButton(dashboard.getString(android.R.string.no), new DialogInterface.OnClickListener() { + .setNegativeButton(activity.getString(android.R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } @@ -233,13 +235,14 @@ public class VpnFragment extends Fragment implements Observer { private void stopBlockingVpn() { Log.d(TAG, "stop VoidVpn!"); - Intent stopVoidVpnIntent = new Intent(dashboard, VoidVpnService.class); + Activity activity = getActivity(); + Intent stopVoidVpnIntent = new Intent(activity, VoidVpnService.class); stopVoidVpnIntent.setAction(EIP_ACTION_STOP_BLOCKING_VPN); - dashboard.startService(stopVoidVpnIntent); + activity.startService(stopVoidVpnIntent); } private void disconnect() { - ProfileManager.setConntectedVpnProfileDisconnected(dashboard); + ProfileManager.setConntectedVpnProfileDisconnected(getActivity()); if (mService != null) { try { mService.stopVPN(false); @@ -255,22 +258,23 @@ public class VpnFragment extends Fragment implements Observer { } private void downloadEIPServiceConfig() { - ProviderAPIResultReceiver provider_api_receiver = new ProviderAPIResultReceiver(new Handler(), dashboard); + ProviderAPIResultReceiver provider_api_receiver = new ProviderAPIResultReceiver(new Handler(), Dashboard.dashboardReceiver); if(eip_receiver != null) ProviderAPICommand.execute(Bundle.EMPTY, ProviderAPI.DOWNLOAD_EIP_SERVICE, provider_api_receiver); } protected void askToStopEIP() { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(dashboard); - alertBuilder.setTitle(dashboard.getString(R.string.eip_cancel_connect_title)) - .setMessage(dashboard.getString(R.string.eip_warning_browser_inconsistency)) + Activity activity = getActivity(); + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity); + alertBuilder.setTitle(activity.getString(R.string.eip_cancel_connect_title)) + .setMessage(activity.getString(R.string.eip_warning_browser_inconsistency)) .setPositiveButton((android.R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { stopEipIfPossible(); } }) - .setNegativeButton(dashboard.getString(android.R.string.no), new DialogInterface.OnClickListener() { + .setNegativeButton(activity.getString(android.R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } @@ -289,18 +293,19 @@ public class VpnFragment extends Fragment implements Observer { * filter for the EIP class */ private void eipCommand(String action) { + Activity activity = getActivity(); // TODO validate "action"...how do we get the list of intent-filters for a class via Android API? - Intent vpn_intent = new Intent(dashboard.getApplicationContext(), EIP.class); + Intent vpn_intent = new Intent(activity.getApplicationContext(), EIP.class); vpn_intent.setAction(action); vpn_intent.putExtra(EIP_RECEIVER, eip_receiver); - dashboard.startService(vpn_intent); + activity.startService(vpn_intent); } @Override public void update(Observable observable, Object data) { if (observable instanceof EipStatus) { eip_status = (EipStatus) observable; - dashboard.runOnUiThread(new Runnable() { + getActivity().runOnUiThread(new Runnable() { @Override public void run() { handleNewState(); @@ -335,12 +340,13 @@ public class VpnFragment extends Fragment implements Observer { } private void updateButton() { + Activity activity = getActivity(); if (eip_status.isConnecting()) { - main_button.setText(dashboard.getString(android.R.string.cancel)); + main_button.setText(activity.getString(android.R.string.cancel)); } else if (eip_status.isConnected() || isOpenVpnRunningWithoutNetwork()) { - main_button.setText(dashboard.getString(R.string.vpn_button_turn_off)); + main_button.setText(activity.getString(R.string.vpn_button_turn_off)); } else { - main_button.setText(dashboard.getString(R.string.vpn_button_turn_on)); + main_button.setText(activity.getString(R.string.vpn_button_turn_on)); } } @@ -358,14 +364,15 @@ public class VpnFragment extends Fragment implements Observer { } private void bindOpenVpnService() { - Intent intent = new Intent(dashboard, OpenVPNService.class); + Activity activity = getActivity(); + Intent intent = new Intent(activity, OpenVPNService.class); intent.setAction(OpenVPNService.START_SERVICE); - dashboard.bindService(intent, openVpnConnection, Context.BIND_AUTO_CREATE); + activity.bindService(intent, openVpnConnection, Context.BIND_AUTO_CREATE); } protected class EIPReceiver extends ResultReceiver { - protected EIPReceiver(Handler handler) { + EIPReceiver(Handler handler) { super(handler); } @@ -375,47 +382,55 @@ public class VpnFragment extends Fragment implements Observer { String request = resultData.getString(EIP_REQUEST); - if (request.equals(EIP_ACTION_START)) { - switch (resultCode) { - case Activity.RESULT_OK: - break; - case Activity.RESULT_CANCELED: + if (request == null) { + return; + } - break; - } - } else if (request.equals(EIP_ACTION_STOP)) { - switch (resultCode) { - case Activity.RESULT_OK: - stop(); - break; - case Activity.RESULT_CANCELED: - break; - } - } else if (request.equals(EIP_NOTIFICATION)) { - switch (resultCode) { - case Activity.RESULT_OK: - break; - case Activity.RESULT_CANCELED: - break; - } - } else if (request.equals(EIP_ACTION_CHECK_CERT_VALIDITY)) { - switch (resultCode) { - case Activity.RESULT_OK: - break; - case Activity.RESULT_CANCELED: - dashboard.downloadVpnCertificate(); - break; - } - } else if (request.equals(EIP_ACTION_UPDATE)) { - switch (resultCode) { - case Activity.RESULT_OK: - if (wants_to_connect) - startEipFromScratch(); - break; - case Activity.RESULT_CANCELED: - handleNewState(); - break; - } + switch (request) { + case EIP_ACTION_START: + switch (resultCode) { + case Activity.RESULT_OK: + break; + case Activity.RESULT_CANCELED: + break; + } + break; + case EIP_ACTION_STOP: + switch (resultCode) { + case Activity.RESULT_OK: + stop(); + break; + case Activity.RESULT_CANCELED: + break; + } + break; + case EIP_NOTIFICATION: + switch (resultCode) { + case Activity.RESULT_OK: + break; + case Activity.RESULT_CANCELED: + break; + } + break; + case EIP_ACTION_CHECK_CERT_VALIDITY: + switch (resultCode) { + case Activity.RESULT_OK: + break; + case Activity.RESULT_CANCELED: + Dashboard.downloadVpnCertificate(); + break; + } + break; + case EIP_ACTION_UPDATE: + switch (resultCode) { + case Activity.RESULT_OK: + if (wants_to_connect) + startEipFromScratch(); + break; + case Activity.RESULT_CANCELED: + handleNewState(); + break; + } } } } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java index a84ab941..998d2c87 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java @@ -16,15 +16,21 @@ */ package se.leap.bitmaskclient.eip; -import android.app.*; -import android.content.*; -import android.os.*; +import android.app.Activity; +import android.app.IntentService; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.ResultReceiver; import android.util.Log; -import org.json.*; +import org.json.JSONException; +import org.json.JSONObject; -import de.blinkt.openvpn.*; -import se.leap.bitmaskclient.*; +import de.blinkt.openvpn.LaunchVPN; +import se.leap.bitmaskclient.OnBootReceiver; +import se.leap.bitmaskclient.VpnFragment; import static se.leap.bitmaskclient.Constants.EIP_ACTION_CHECK_CERT_VALIDITY; import static se.leap.bitmaskclient.Constants.EIP_ACTION_IS_RUNNING; diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnCertificateValidator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnCertificateValidator.java index 28099f06..197a080b 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnCertificateValidator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnCertificateValidator.java @@ -16,10 +16,13 @@ */ package se.leap.bitmaskclient.eip; -import java.security.cert.*; -import java.util.*; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.util.Calendar; +import java.util.Date; -import se.leap.bitmaskclient.*; +import se.leap.bitmaskclient.ConfigHelper; public class VpnCertificateValidator { public final static String TAG = VpnCertificateValidator.class.getSimpleName(); diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java index 54563ec4..b1318def 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java @@ -16,11 +16,14 @@ */ package se.leap.bitmaskclient.eip; -import org.json.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; -import java.util.*; +import java.util.Iterator; -import se.leap.bitmaskclient.*; +import se.leap.bitmaskclient.Constants; +import se.leap.bitmaskclient.Provider; public class VpnConfigGenerator { diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java index 14323f8e..f4be3ea1 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java @@ -28,7 +28,6 @@ import se.leap.bitmaskclient.R; public class UserStatusFragment extends Fragment implements Observer, SessionDialog.SessionDialogInterface { public static String TAG = UserStatusFragment.class.getSimpleName(); - private static Dashboard dashboard; private ProviderAPIResultReceiver providerAPI_result_receiver; @InjectView(R.id.user_status_username) @@ -74,16 +73,14 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia @Override public void onAttach(Activity activity) { super.onAttach(activity); - dashboard = (Dashboard) activity; - - providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), dashboard); + providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), Dashboard.dashboardReceiver); } public void restoreSessionStatus(Bundle savedInstanceState) { if (savedInstanceState != null) if (savedInstanceState.containsKey(UserStatus.TAG)) { UserStatus.SessionStatus status = (UserStatus.SessionStatus) savedInstanceState.getSerializable(UserStatus.TAG); - this.status.updateStatus(status, getResources()); + UserStatus.updateStatus(status, getResources()); } } @@ -93,7 +90,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia if(status.isLoggedIn()) logOut(); else if(status.isLoggedOut()) - dashboard.sessionDialog(Bundle.EMPTY); + Dashboard.sessionDialog(Bundle.EMPTY); else if(status.inProgress()) cancelLoginOrSignup(); } @@ -102,7 +99,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia public void update(Observable observable, Object data) { if (observable instanceof UserStatus) { final UserStatus status = (UserStatus) observable; - dashboard.runOnUiThread(new Runnable() { + getActivity().runOnUiThread(new Runnable() { @Override public void run() { handleNewStatus(status); @@ -138,12 +135,12 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia private void updateButton() { if(status.isLoggedIn() || status.didntLogOut()) - button.setText(dashboard.getString(R.string.logout_button)); + button.setText(getActivity().getString(R.string.logout_button)); else if(allows_registration) { if (status.isLoggedOut() || status.notLoggedIn()) - button.setText(dashboard.getString(R.string.login_button)); + button.setText(getActivity().getString(R.string.login_button)); else if (status.inProgress()) - button.setText(dashboard.getString(android.R.string.cancel)); + button.setText(getActivity().getString(android.R.string.cancel)); } } -- cgit v1.2.3 From 4f7200c55032d17c9bdbdb30cfd83dc757c63fe7 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 19 Dec 2017 17:37:57 +0100 Subject: adjust Fragments --- .../bitmaskclient/BaseConfigurationWizard.java | 10 ++--- .../main/java/se/leap/bitmaskclient/Dashboard.java | 16 ++++---- .../leap/bitmaskclient/DownloadFailedDialog.java | 9 +++-- .../bitmaskclient/FragmentManagerEnhanced.java | 4 +- .../java/se/leap/bitmaskclient/MainActivity.java | 46 +++++++++++++++++----- .../bitmaskclient/NavigationDrawerFragment.java | 4 +- .../java/se/leap/bitmaskclient/VpnFragment.java | 22 ++++++----- .../bitmaskclient/userstatus/SessionDialog.java | 21 +++++----- .../userstatus/UserStatusFragment.java | 5 ++- 9 files changed, 89 insertions(+), 48 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 52c8f8e5..75a653c0 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -17,9 +17,6 @@ package se.leap.bitmaskclient; -import android.app.Activity; -import android.app.DialogFragment; -import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -27,6 +24,9 @@ import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; +import android.support.v4.app.DialogFragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.app.AppCompatActivity; import android.view.Display; import android.view.Menu; import android.view.MenuItem; @@ -68,7 +68,7 @@ import static android.view.View.VISIBLE; * @author cyberta */ -public abstract class BaseConfigurationWizard extends Activity +public abstract class BaseConfigurationWizard extends AppCompatActivity implements NewProviderDialog.NewProviderDialogInterface, ProviderDetailFragment.ProviderDetailFragmentInterface, DownloadFailedDialog.DownloadFailedDialogInterface, ProviderAPIResultReceiver.Receiver { @InjectView(R.id.progressbar_configuration_wizard) protected ProgressBar mProgressBar; @@ -134,7 +134,7 @@ public abstract class BaseConfigurationWizard extends Activity protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); - fragment_manager = new FragmentManagerEnhanced(getFragmentManager()); + fragment_manager = new FragmentManagerEnhanced(getSupportFragmentManager()); provider_manager = ProviderManager.getInstance(getAssets(), getExternalFilesDir(null)); setUpInitialUI(); diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 1eed484c..0d3af13f 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -17,15 +17,15 @@ package se.leap.bitmaskclient; import android.annotation.SuppressLint; -import android.app.Activity; import android.app.AlertDialog; -import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.os.Handler; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; @@ -56,7 +56,7 @@ import static se.leap.bitmaskclient.Constants.REQUEST_CODE_SWITCH_PROVIDER; * @author Sean Leonard * @author parmegv */ -public class Dashboard extends Activity { +public class Dashboard extends AppCompatActivity { public static final String TAG = Dashboard.class.getSimpleName(); @@ -91,7 +91,7 @@ public class Dashboard extends Activity { super.onCreate(savedInstanceState); dashboardReceiver = new DashboardReceiver(this); preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); - fragment_manager = new FragmentManagerEnhanced(getFragmentManager()); + fragment_manager = new FragmentManagerEnhanced(getSupportFragmentManager()); providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), dashboardReceiver); @@ -305,7 +305,7 @@ public class Dashboard extends Activity { * has caused to start Dashboard * @return the created VPNFragment */ - private VpnFragment prepareEipFragment(boolean hideAndTurnOnEipOnBoot) { + public static VpnFragment prepareEipFragment(boolean hideAndTurnOnEipOnBoot) { VpnFragment eip_fragment = new VpnFragment(); if (hideAndTurnOnEipOnBoot && !isAlwaysOn()) { @@ -323,7 +323,7 @@ public class Dashboard extends Activity { * checks if Android's VPN feature 'always-on' is enabled for Bitmask * @return true if 'always-on' is enabled false if not */ - private boolean isAlwaysOn() { + private static boolean isAlwaysOn() { return preferences.getBoolean(EIP_IS_ALWAYS_ON, false); } @@ -418,11 +418,11 @@ public class Dashboard extends Activity { String password = resultData.getString(SessionDialog.PASSWORD); dashboard.user_status_fragment.logIn(username, password); } else if (resultCode == ProviderAPI.FAILED_SIGNUP) { - Dashboard.sessionDialog(resultData); + MainActivity.sessionDialog(resultData); } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGIN) { Dashboard.downloadVpnCertificate(); } else if (resultCode == ProviderAPI.FAILED_LOGIN) { - Dashboard.sessionDialog(resultData); + MainActivity.sessionDialog(resultData); } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGOUT) { if (switching_provider) dashboard.switchProvider(); } else if (resultCode == ProviderAPI.LOGOUT_FAILED) { diff --git a/app/src/main/java/se/leap/bitmaskclient/DownloadFailedDialog.java b/app/src/main/java/se/leap/bitmaskclient/DownloadFailedDialog.java index da32dbd4..d6d89b58 100644 --- a/app/src/main/java/se/leap/bitmaskclient/DownloadFailedDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/DownloadFailedDialog.java @@ -16,9 +16,12 @@ */ package se.leap.bitmaskclient; -import android.app.*; -import android.content.*; -import android.os.*; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.v4.app.DialogFragment; /** * Implements a dialog to show why a download failed. diff --git a/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java b/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java index 8ba7fa34..9594cea0 100644 --- a/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java +++ b/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java @@ -16,7 +16,9 @@ */ package se.leap.bitmaskclient; -import android.app.*; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; public class FragmentManagerEnhanced { diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java index 8cd6357c..2f07f162 100644 --- a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -2,9 +2,12 @@ package se.leap.bitmaskclient; import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; @@ -14,11 +17,17 @@ import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import se.leap.bitmaskclient.fragments.LogFragment; +import se.leap.bitmaskclient.userstatus.SessionDialog; public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks { + private static Provider provider = new Provider(); + private static FragmentManagerEnhanced fragmentManager; + private SharedPreferences preferences; + + /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ @@ -40,42 +49,52 @@ public class MainActivity extends AppCompatActivity getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); + fragmentManager = new FragmentManagerEnhanced(getSupportFragmentManager()); + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); + } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); - Fragment fragment; + Fragment fragment = null; switch (position) { case 1: + // TODO STOP VPN + // if (provider.hasEIP()) eip_fragment.stopEipIfPossible(); + preferences.edit().clear().apply(); + startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); + break; case 2: - fragment = PlaceholderFragment.newInstance(); + fragment = new LogFragment(); break; default: - fragment = new LogFragment(); + fragment = new VpnFragment(); break; } - fragmentManager.beginTransaction() - .replace(R.id.container, fragment) - .commit(); + if (fragment != null) { + fragmentManager.beginTransaction() + .replace(R.id.container, fragment) + .commit(); + } onSectionAttached(position); } public void onSectionAttached(int number) { switch (number) { case 1: - mTitle = getString(R.string.title_section2); + mTitle = getString(R.string.switch_provider_menu_option); break; case 2: - mTitle = getString(R.string.title_section3); + mTitle = getString(R.string.log_fragment_title); break; default: - mTitle = getString(R.string.log_fragment_title); + mTitle = getString(R.string.vpn_fragment_title); break; } restoreActionBar(); @@ -118,4 +137,13 @@ public class MainActivity extends AppCompatActivity } } + public static void sessionDialog(Bundle resultData) { + try { + FragmentTransaction transaction = fragmentManager.removePreviousFragment(SessionDialog.TAG); + SessionDialog.getInstance(provider, resultData).show(transaction, SessionDialog.TAG); + } catch (IllegalStateException e) { + e.printStackTrace(); + } + } + } diff --git a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java index bb0d8f46..b8a9e5b1 100644 --- a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java @@ -123,9 +123,9 @@ public class NavigationDrawerFragment extends Fragment { android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ + getString(R.string.vpn_fragment_title), + getString(R.string.switch_provider_menu_option), getString(R.string.log_fragment_title), - getString(R.string.title_section2), - getString(R.string.title_section3), })); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); mFragmentContainerView = activity.findViewById(fragmentId); diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index 2b968769..e16ab75c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -18,7 +18,6 @@ package se.leap.bitmaskclient; import android.app.Activity; import android.app.AlertDialog; -import android.app.Fragment; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; @@ -30,6 +29,7 @@ import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.os.ResultReceiver; +import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -127,7 +127,6 @@ public class VpnFragment extends Fragment implements Observer { if (arguments != null && arguments.containsKey(START_EIP_ON_BOOT) && arguments.getBoolean(START_EIP_ON_BOOT)) { startEipFromScratch(); } - return view; } @@ -170,7 +169,7 @@ public class VpnFragment extends Fragment implements Observer { else if (canLogInToStartEIP()) { wants_to_connect = true; Bundle bundle = new Bundle(); - Dashboard.sessionDialog(bundle); + MainActivity.sessionDialog(bundle); } else { Log.d(TAG, "WHAT IS GOING ON HERE?!"); // TODO: implement a fallback: check if vpncertificate was not downloaded properly or give @@ -305,12 +304,17 @@ public class VpnFragment extends Fragment implements Observer { public void update(Observable observable, Object data) { if (observable instanceof EipStatus) { eip_status = (EipStatus) observable; - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - handleNewState(); - } - }); + Activity activity = getActivity(); + if (activity != null) { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + handleNewState(); + } + }); + } else { + Log.e("VpnFragment", "activity is null"); + } } } diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java index 61349490..440b02fa 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java @@ -16,15 +16,18 @@ */ package se.leap.bitmaskclient.userstatus; -import android.app.*; -import android.content.*; -import android.os.*; -import android.view.*; -import android.widget.*; - -import butterknife.*; -import se.leap.bitmaskclient.ProviderAPI; -import se.leap.bitmaskclient.VpnFragment; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.v4.app.DialogFragment; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.EditText; +import android.widget.TextView; + +import butterknife.ButterKnife; +import butterknife.InjectView; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.R; diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java index f4be3ea1..a991e88e 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java @@ -1,9 +1,9 @@ package se.leap.bitmaskclient.userstatus; import android.app.Activity; -import android.app.Fragment; import android.os.Bundle; import android.os.Handler; +import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -19,6 +19,7 @@ import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import se.leap.bitmaskclient.Dashboard; +import se.leap.bitmaskclient.MainActivity; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.ProviderAPI; import se.leap.bitmaskclient.ProviderAPICommand; @@ -90,7 +91,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia if(status.isLoggedIn()) logOut(); else if(status.isLoggedOut()) - Dashboard.sessionDialog(Bundle.EMPTY); + MainActivity.sessionDialog(Bundle.EMPTY); else if(status.inProgress()) cancelLoginOrSignup(); } -- cgit v1.2.3 From bd99fc61a2e8217c41b70c6f2ff0df87e7008ea0 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Mon, 8 Jan 2018 15:49:34 +0100 Subject: seperate accountList and settingsList in drawer --- .../java/se/leap/bitmaskclient/MainActivity.java | 57 +--- .../bitmaskclient/NavigationDrawerFragment.java | 282 ----------------- .../java/se/leap/bitmaskclient/StartActivity.java | 2 +- .../drawer/NavigationDrawerFragment.java | 349 +++++++++++++++++++++ .../leap/bitmaskclient/fragments/LogFragment.java | 2 - .../bitmaskclient/userstatus/SessionDialog.java | 7 +- .../userstatus/UserStatusFragment.java | 4 +- 7 files changed, 361 insertions(+), 342 deletions(-) delete mode 100644 app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java index 2f07f162..82a193e7 100644 --- a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -11,17 +11,20 @@ import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; +import se.leap.bitmaskclient.drawer.NavigationDrawerFragment; import se.leap.bitmaskclient.fragments.LogFragment; import se.leap.bitmaskclient.userstatus.SessionDialog; +import se.leap.bitmaskclient.userstatus.User; +import se.leap.bitmaskclient.userstatus.UserStatusFragment; -public class MainActivity extends AppCompatActivity - implements NavigationDrawerFragment.NavigationDrawerCallbacks { +public class MainActivity extends AppCompatActivity { private static Provider provider = new Provider(); private static FragmentManagerEnhanced fragmentManager; @@ -58,56 +61,6 @@ public class MainActivity extends AppCompatActivity } - @Override - public void onNavigationDrawerItemSelected(int position) { - // update the main content by replacing fragments - FragmentManager fragmentManager = getSupportFragmentManager(); - Fragment fragment = null; - switch (position) { - case 1: - // TODO STOP VPN - // if (provider.hasEIP()) eip_fragment.stopEipIfPossible(); - preferences.edit().clear().apply(); - startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); - break; - case 2: - fragment = new LogFragment(); - break; - default: - fragment = new VpnFragment(); - break; - } - if (fragment != null) { - fragmentManager.beginTransaction() - .replace(R.id.container, fragment) - .commit(); - } - onSectionAttached(position); - } - - public void onSectionAttached(int number) { - switch (number) { - case 1: - mTitle = getString(R.string.switch_provider_menu_option); - break; - case 2: - mTitle = getString(R.string.log_fragment_title); - break; - default: - mTitle = getString(R.string.vpn_fragment_title); - break; - } - restoreActionBar(); - } - - public void restoreActionBar() { - ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setDisplayShowTitleEnabled(true); - actionBar.setSubtitle(mTitle); - } - } - /** * A placeholder fragment containing a simple view. */ diff --git a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java deleted file mode 100644 index b8a9e5b1..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/NavigationDrawerFragment.java +++ /dev/null @@ -1,282 +0,0 @@ -package se.leap.bitmaskclient; - - -import android.content.Context; -import android.support.v7.app.ActionBarDrawerToggle; -import android.support.v4.app.Fragment; -import android.support.v4.view.GravityCompat; -import android.support.v4.widget.DrawerLayout; -import android.content.SharedPreferences; -import android.content.res.Configuration; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.v7.app.ActionBar; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.Toast; - -/** - * Fragment used for managing interactions for and presentation of a navigation drawer. - * See the - * design guidelines for a complete explanation of the behaviors implemented here. - */ -public class NavigationDrawerFragment extends Fragment { - - /** - * Remember the position of the selected item. - */ - private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; - - /** - * Per the design guidelines, you should show the drawer on launch until the user manually - * expands it. This shared preference tracks this. - */ - private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; - - /** - * A pointer to the current callbacks instance (the Activity). - */ - private NavigationDrawerCallbacks mCallbacks; - - /** - * Helper component that ties the action bar to the navigation drawer. - */ - private ActionBarDrawerToggle mDrawerToggle; - - private DrawerLayout mDrawerLayout; - private View mDrawerView; - private ListView mDrawerListView; - private View mFragmentContainerView; - - private int mCurrentSelectedPosition = 0; - private boolean mFromSavedInstanceState; - private boolean mUserLearnedDrawer; - - public NavigationDrawerFragment() { - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // Read in the flag indicating whether or not the user has demonstrated awareness of the - // drawer. See PREF_USER_LEARNED_DRAWER for details. - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); - mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); - - if (savedInstanceState != null) { - mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); - mFromSavedInstanceState = true; - } - - // Select either the default item (0) or the last selected item. - selectItem(mCurrentSelectedPosition); - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - // Indicate that this fragment would like to influence the set of actions in the action bar. - setHasOptionsMenu(true); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - mDrawerView = inflater.inflate(R.layout.drawer_main, container, false); - return mDrawerView; - } - - public boolean isDrawerOpen() { - return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); - } - - /** - * Users of this fragment must call this method to set up the navigation drawer interactions. - * - * @param fragmentId The android:id of this fragment in its activity's layout. - * @param drawerLayout The DrawerLayout containing this fragment's UI. - */ - public void setUp(int fragmentId, DrawerLayout drawerLayout) { - AppCompatActivity activity = (AppCompatActivity) getActivity(); - - mDrawerListView = mDrawerView.findViewById(R.id.accountList); - mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - selectItem(position); - } - }); - - ActionBar actionBar = activity.getSupportActionBar(); - mDrawerListView.setAdapter(new ArrayAdapter( - actionBar.getThemedContext(), - android.R.layout.simple_list_item_activated_1, - android.R.id.text1, - new String[]{ - getString(R.string.vpn_fragment_title), - getString(R.string.switch_provider_menu_option), - getString(R.string.log_fragment_title), - })); - mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); - mFragmentContainerView = activity.findViewById(fragmentId); - mDrawerLayout = drawerLayout; - - // set a custom shadow that overlays the main content when the drawer opens - mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); - - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setHomeButtonEnabled(true); - // ActionBarDrawerToggle ties together the the proper interactions - // between the navigation drawer and the action bar app icon. - mDrawerToggle = new ActionBarDrawerToggle( - getActivity(), - mDrawerLayout, - (Toolbar) drawerLayout.findViewById(R.id.toolbar), - R.string.navigation_drawer_open, - R.string.navigation_drawer_close - ) { - @Override - public void onDrawerClosed(View drawerView) { - super.onDrawerClosed(drawerView); - if (!isAdded()) { - return; - } - - getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() - } - - @Override - public void onDrawerOpened(View drawerView) { - super.onDrawerOpened(drawerView); - if (!isAdded()) { - return; - } - - if (!mUserLearnedDrawer) { - // The user manually opened the drawer; store this flag to prevent auto-showing - // the navigation drawer automatically in the future. - mUserLearnedDrawer = true; - SharedPreferences sp = PreferenceManager - .getDefaultSharedPreferences(getActivity()); - sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); - } - - getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() - } - }; - - // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, - // per the navigation drawer design guidelines. - if (!mUserLearnedDrawer && !mFromSavedInstanceState) { - mDrawerLayout.openDrawer(mFragmentContainerView); - } - - // Defer code dependent on restoration of previous instance state. - mDrawerLayout.post(new Runnable() { - @Override - public void run() { - mDrawerToggle.syncState(); - } - }); - - mDrawerLayout.addDrawerListener(mDrawerToggle); - } - - private void selectItem(int position) { - mCurrentSelectedPosition = position; - if (mDrawerListView != null) { - mDrawerListView.setItemChecked(position, true); - } - if (mDrawerLayout != null) { - mDrawerLayout.closeDrawer(mFragmentContainerView); - } - if (mCallbacks != null) { - mCallbacks.onNavigationDrawerItemSelected(position); - } - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - try { - mCallbacks = (NavigationDrawerCallbacks) context; - } catch (ClassCastException e) { - throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); - } - } - - @Override - public void onDetach() { - super.onDetach(); - mCallbacks = null; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - // Forward the new configuration the drawer toggle component. - mDrawerToggle.onConfigurationChanged(newConfig); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - if (mDrawerLayout != null && isDrawerOpen()) { - showGlobalContextActionBar(); - } - super.onCreateOptionsMenu(menu, inflater); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (mDrawerToggle.onOptionsItemSelected(item)) { - return true; - } - - if (item.getItemId() == R.id.action_example) { - Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show(); - return true; - } - - return super.onOptionsItemSelected(item); - } - - /** - * Per the navigation drawer design guidelines, updates the action bar to show the global app - * 'context', rather than just what's in the current screen. - */ - private void showGlobalContextActionBar() { - ActionBar actionBar = getActionBar(); - actionBar.setDisplayShowTitleEnabled(true); - actionBar.setTitle(R.string.app_name); - } - - private ActionBar getActionBar() { - return ((AppCompatActivity) getActivity()).getSupportActionBar(); - } - - /** - * Callbacks interface that all activities using this fragment must implement. - */ - public interface NavigationDrawerCallbacks { - /** - * Called when an item in the navigation drawer is selected. - */ - void onNavigationDrawerItemSelected(int position); - } -} diff --git a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java index 1bf81aea..55760cb3 100644 --- a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java @@ -48,7 +48,7 @@ public class StartActivity extends Activity { break; case FIRST: - // TODO start ProfileCreation & replace below code + // (new Intent(getActivity(), ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); break; case UPGRADE: diff --git a/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java new file mode 100644 index 00000000..60c38fbc --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java @@ -0,0 +1,349 @@ +package se.leap.bitmaskclient.drawer; + + +import android.content.Context; +import android.content.Intent; +import android.support.v4.app.FragmentManager; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v4.app.Fragment; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; +import android.content.SharedPreferences; +import android.content.res.Configuration; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.Toast; + +import se.leap.bitmaskclient.ConfigurationWizard; +import se.leap.bitmaskclient.Constants; +import se.leap.bitmaskclient.Provider; +import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.VpnFragment; +import se.leap.bitmaskclient.fragments.LogFragment; +import se.leap.bitmaskclient.userstatus.User; +import se.leap.bitmaskclient.userstatus.UserStatusFragment; + +/** + * Fragment used for managing interactions for and presentation of a navigation drawer. + * See the + * design guidelines for a complete explanation of the behaviors implemented here. + */ +public class NavigationDrawerFragment extends Fragment { + + /** + * Remember the position of the selected item. + */ + private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; + + /** + * Per the design guidelines, you should show the drawer on launch until the user manually + * expands it. This shared preference tracks this. + */ + private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; + + /** + * Helper component that ties the action bar to the navigation drawer. + */ + private ActionBarDrawerToggle mDrawerToggle; + + private DrawerLayout mDrawerLayout; + private View mDrawerView; + private ListView mDrawerSettingsListView; + private ListView mDrawerAccountsListView; + private View mFragmentContainerView; + + private int mCurrentSelectedPosition = 0; + private boolean mFromSavedInstanceState; + private boolean mUserLearnedDrawer; + + private String mTitle; + + private SharedPreferences preferences; + + public NavigationDrawerFragment() { + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Read in the flag indicating whether or not the user has demonstrated awareness of the + // drawer. See PREF_USER_LEARNED_DRAWER for details. + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); + mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); + + preferences = getActivity().getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); + + if (savedInstanceState != null) { + mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); + mFromSavedInstanceState = true; + } + + // Select either the default item (0) or the last selected item. + if (mDrawerSettingsListView != null) { + selectItem(mDrawerSettingsListView, mCurrentSelectedPosition); + } + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + // Indicate that this fragment would like to influence the set of actions in the action bar. + setHasOptionsMenu(true); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + mDrawerView = inflater.inflate(R.layout.drawer_main, container, false); + return mDrawerView; + } + + public boolean isDrawerOpen() { + return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); + } + + /** + * Users of this fragment must call this method to set up the navigation drawer interactions. + * + * @param fragmentId The android:id of this fragment in its activity's layout. + * @param drawerLayout The DrawerLayout containing this fragment's UI. + */ + public void setUp(int fragmentId, DrawerLayout drawerLayout) { + AppCompatActivity activity = (AppCompatActivity) getActivity(); + ActionBar actionBar = activity.getSupportActionBar(); + + mDrawerSettingsListView = mDrawerView.findViewById(R.id.settingsList); + mDrawerSettingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + selectItem(parent, position); + } + }); + + mDrawerSettingsListView.setAdapter(new ArrayAdapter( + actionBar.getThemedContext(), + android.R.layout.simple_list_item_activated_1, + android.R.id.text1, + new String[]{ + getString(R.string.vpn_fragment_title), + getString(R.string.switch_provider_menu_option), + getString(R.string.log_fragment_title), + })); + mDrawerSettingsListView.setItemChecked(mCurrentSelectedPosition, true); + + mDrawerAccountsListView = mDrawerView.findViewById(R.id.accountList); + mDrawerAccountsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + selectItem(parent, position); + } + }); + + mDrawerAccountsListView.setAdapter(new ArrayAdapter( + actionBar.getThemedContext(), + android.R.layout.simple_list_item_activated_1, + android.R.id.text1, + new String[]{ + User.userName(), + })); + mDrawerAccountsListView.setItemChecked(mCurrentSelectedPosition, true); + + mFragmentContainerView = activity.findViewById(fragmentId); + mDrawerLayout = drawerLayout; + + // set a custom shadow that overlays the main content when the drawer opens + mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + + actionBar.setDisplayHomeAsUpEnabled(true); + actionBar.setHomeButtonEnabled(true); + // ActionBarDrawerToggle ties together the the proper interactions + // between the navigation drawer and the action bar app icon. + mDrawerToggle = new ActionBarDrawerToggle( + getActivity(), + mDrawerLayout, + (Toolbar) drawerLayout.findViewById(R.id.toolbar), + R.string.navigation_drawer_open, + R.string.navigation_drawer_close + ) { + @Override + public void onDrawerClosed(View drawerView) { + super.onDrawerClosed(drawerView); + if (!isAdded()) { + return; + } + + getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() + } + + @Override + public void onDrawerOpened(View drawerView) { + super.onDrawerOpened(drawerView); + if (!isAdded()) { + return; + } + + if (!mUserLearnedDrawer) { + // The user manually opened the drawer; store this flag to prevent auto-showing + // the navigation drawer automatically in the future. + mUserLearnedDrawer = true; + SharedPreferences sp = PreferenceManager + .getDefaultSharedPreferences(getActivity()); + sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); + } + + getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() + } + }; + + // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, + // per the navigation drawer design guidelines. + if (!mUserLearnedDrawer && !mFromSavedInstanceState) { + mDrawerLayout.openDrawer(mFragmentContainerView); + } + + // Defer code dependent on restoration of previous instance state. + mDrawerLayout.post(new Runnable() { + @Override + public void run() { + mDrawerToggle.syncState(); + } + }); + mDrawerLayout.addDrawerListener(mDrawerToggle); + + selectItem(mDrawerSettingsListView, 0); + } + + private void selectItem(AdapterView list, int position) { + mCurrentSelectedPosition = position; + if (list != null) { + ((ListView) list).setItemChecked(position, true); + } + if (mDrawerLayout != null) { + mDrawerLayout.closeDrawer(mFragmentContainerView); + } + onNavigationDrawerItemSelected(list, position); + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + } + + @Override + public void onDetach() { + super.onDetach(); + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + // Forward the new configuration the drawer toggle component. + mDrawerToggle.onConfigurationChanged(newConfig); + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + if (mDrawerLayout != null && isDrawerOpen()) { + showGlobalContextActionBar(); + } + super.onCreateOptionsMenu(menu, inflater); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (mDrawerToggle.onOptionsItemSelected(item)) { + return true; + } + + if (item.getItemId() == R.id.action_example) { + Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show(); + return true; + } + + return super.onOptionsItemSelected(item); + } + + /** + * Per the navigation drawer design guidelines, updates the action bar to show the global app + * 'context', rather than just what's in the current screen. + */ + private void showGlobalContextActionBar() { + ActionBar actionBar = getActionBar(); + actionBar.setDisplayShowTitleEnabled(true); + actionBar.setTitle(R.string.app_name); + } + + private ActionBar getActionBar() { + return ((AppCompatActivity) getActivity()).getSupportActionBar(); + } + + public void onNavigationDrawerItemSelected(AdapterView parent, int position) { + // update the main content by replacing fragments + FragmentManager fragmentManager = getFragmentManager(); + Fragment fragment = null; + + if (parent == mDrawerAccountsListView) { + mTitle = User.userName(); + fragment = new UserStatusFragment(); + Bundle bundle = new Bundle(); + bundle.putBoolean(Provider.ALLOW_REGISTRATION, new Provider().allowsRegistration()); + fragment.setArguments(bundle); + } else { + Log.d("Drawer", String.format("Selected position %d", position)); + switch (position) { + case 1: + // TODO STOP VPN + // if (provider.hasEIP()) eip_fragment.stopEipIfPossible(); + preferences.edit().clear().apply(); + startActivityForResult(new Intent(getActivity(), ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); + break; + case 2: + mTitle = getString(R.string.log_fragment_title); + fragment = new LogFragment(); + break; + default: + mTitle = getString(R.string.vpn_fragment_title); + fragment = new VpnFragment(); + break; + } + } + + if (fragment != null) { + fragmentManager.beginTransaction() + .replace(R.id.container, fragment) + .commit(); + } + + restoreActionBar(); + } + + public void restoreActionBar() { + ActionBar actionBar = getActionBar(); + if (actionBar != null) { + actionBar.setDisplayShowTitleEnabled(true); + actionBar.setSubtitle(mTitle); + } + } + + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java b/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java index b72e53d5..3917683d 100644 --- a/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java @@ -25,7 +25,6 @@ import android.os.Message; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v4.app.ListFragment; -import android.support.v7.app.AppCompatActivity; import android.text.SpannableString; import android.text.format.DateFormat; import android.text.style.ImageSpan; @@ -65,7 +64,6 @@ import de.blinkt.openvpn.core.VpnStatus; import de.blinkt.openvpn.core.VpnStatus.LogListener; import de.blinkt.openvpn.core.VpnStatus.StateListener; import se.leap.bitmaskclient.Dashboard; -import se.leap.bitmaskclient.NavigationDrawerFragment; import se.leap.bitmaskclient.R; import static de.blinkt.openvpn.core.OpenVPNService.humanReadableByteCount; diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java index 440b02fa..1256c619 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java @@ -16,11 +16,12 @@ */ package se.leap.bitmaskclient.userstatus; -import android.app.Activity; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; +import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; @@ -164,11 +165,11 @@ public class SessionDialog extends DialogFragment { SessionDialogInterface interface_with_Dashboard; @Override - public void onAttach(Activity activity) { + public void onAttach(Context activity) { super.onAttach(activity); try { - interface_with_Dashboard = (SessionDialogInterface) activity.getFragmentManager().findFragmentById(R.id.user_status_fragment);; + interface_with_Dashboard = (SessionDialogInterface) ((AppCompatActivity) activity).getSupportFragmentManager().getFragments().get(0); } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement LogInDialogListener"); diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java index a991e88e..a6439a16 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java @@ -1,6 +1,6 @@ package se.leap.bitmaskclient.userstatus; -import android.app.Activity; +import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; @@ -72,7 +72,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia } @Override - public void onAttach(Activity activity) { + public void onAttach(Context activity) { super.onAttach(activity); providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), Dashboard.dashboardReceiver); } -- cgit v1.2.3 From 245982bdb6fda879827ab3c89617b8dd591fb7f4 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Mon, 8 Jan 2018 16:11:23 +0100 Subject: AboutActivity to AboutFragment --- .../java/se/leap/bitmaskclient/AboutActivity.java | 35 ---------------- .../bitmaskclient/BaseConfigurationWizard.java | 5 ++- .../main/java/se/leap/bitmaskclient/Dashboard.java | 3 +- .../drawer/NavigationDrawerFragment.java | 6 +++ .../bitmaskclient/fragments/AboutFragment.java | 49 ++++++++++++++++++++++ 5 files changed, 60 insertions(+), 38 deletions(-) delete mode 100644 app/src/main/java/se/leap/bitmaskclient/AboutActivity.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/fragments/AboutFragment.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/AboutActivity.java b/app/src/main/java/se/leap/bitmaskclient/AboutActivity.java deleted file mode 100644 index 4ebae32d..00000000 --- a/app/src/main/java/se/leap/bitmaskclient/AboutActivity.java +++ /dev/null @@ -1,35 +0,0 @@ -package se.leap.bitmaskclient; - -import android.app.*; -import android.content.pm.*; -import android.content.pm.PackageManager.*; -import android.os.*; -import android.widget.*; - -public class AboutActivity extends Activity { - - final public static String TAG = "aboutFragment"; - final public static int VIEWED = 0; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.about); - TextView ver = (TextView) findViewById(R.id.version); - - String version; - String name = "Bitmask"; - try { - PackageInfo packageinfo = getPackageManager().getPackageInfo(getPackageName(), 0); - version = packageinfo.versionName; - name = getString(R.string.app_name); - } catch (NameNotFoundException e) { - version = "error fetching version"; - } - - - ver.setText(getString(R.string.version_info, name, version)); - setResult(VIEWED); - } - -} diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 75a653c0..9f12ed9a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -51,6 +51,7 @@ import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnItemClick; +import se.leap.bitmaskclient.fragments.AboutFragment; import se.leap.bitmaskclient.userstatus.SessionDialog; import static android.view.View.GONE; @@ -246,7 +247,7 @@ public abstract class BaseConfigurationWizard extends AppCompatActivity mConfigState.setAction(PROVIDER_NOT_SET); hideProgressBar(); setResult(RESULT_CANCELED, mConfigState); - } else if (resultCode == AboutActivity.VIEWED) { + } else if (resultCode == AboutFragment.VIEWED) { // Do nothing, right now // I need this for CW to wait for the About activity to end before going back to Dashboard. } @@ -417,7 +418,7 @@ public abstract class BaseConfigurationWizard extends AppCompatActivity public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about_leap: - startActivityForResult(new Intent(this, AboutActivity.class), 0); + startActivityForResult(new Intent(this, AboutFragment.class), 0); return true; case R.id.new_provider: addAndSelectNewProvider(); diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 0d3af13f..8c33a6cd 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -40,6 +40,7 @@ import java.net.URL; import butterknife.ButterKnife; import butterknife.InjectView; +import se.leap.bitmaskclient.fragments.AboutFragment; import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; @@ -365,7 +366,7 @@ public class Dashboard extends AppCompatActivity { } public void showAbout() { - Intent intent = new Intent(this, AboutActivity.class); + Intent intent = new Intent(this, AboutFragment.class); startActivity(intent); } diff --git a/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java index 60c38fbc..e7217ad1 100644 --- a/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java @@ -32,6 +32,7 @@ import se.leap.bitmaskclient.Constants; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.VpnFragment; +import se.leap.bitmaskclient.fragments.AboutFragment; import se.leap.bitmaskclient.fragments.LogFragment; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; @@ -142,6 +143,7 @@ public class NavigationDrawerFragment extends Fragment { getString(R.string.vpn_fragment_title), getString(R.string.switch_provider_menu_option), getString(R.string.log_fragment_title), + getString(R.string.about_fragment_title), })); mDrawerSettingsListView.setItemChecked(mCurrentSelectedPosition, true); @@ -321,6 +323,10 @@ public class NavigationDrawerFragment extends Fragment { mTitle = getString(R.string.log_fragment_title); fragment = new LogFragment(); break; + case 3: + mTitle = getString(R.string.about_fragment_title); + fragment = new AboutFragment(); + break; default: mTitle = getString(R.string.vpn_fragment_title); fragment = new VpnFragment(); diff --git a/app/src/main/java/se/leap/bitmaskclient/fragments/AboutFragment.java b/app/src/main/java/se/leap/bitmaskclient/fragments/AboutFragment.java new file mode 100644 index 00000000..113ce397 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/fragments/AboutFragment.java @@ -0,0 +1,49 @@ +package se.leap.bitmaskclient.fragments; + +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager.NameNotFoundException; +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import butterknife.ButterKnife; +import butterknife.InjectView; +import se.leap.bitmaskclient.R; + +public class AboutFragment extends Fragment { + + final public static String TAG = "aboutFragment"; + final public static int VIEWED = 0; + + @InjectView(R.id.version) + TextView versionTextView; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.about, container, false); + ButterKnife.inject(this, view); + return view; + } + + @Override + public void onStart() { + super.onStart(); + String version; + String name = "Bitmask"; + try { + PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo( + getActivity().getPackageName(), 0); + version = packageinfo.versionName; + name = getString(R.string.app_name); + } catch (NameNotFoundException e) { + version = "error fetching version"; + } + + versionTextView.setText(getString(R.string.version_info, name, version)); + } + +} -- cgit v1.2.3 From 3addd20598f7fee2d41a24d64b375a2f63874457 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 9 Jan 2018 14:02:57 +0100 Subject: create ProviderDetail Activity --- .../bitmaskclient/BaseConfigurationWizard.java | 45 +++------------------- 1 file changed, 5 insertions(+), 40 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 9f12ed9a..601615b6 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -70,7 +70,7 @@ import static android.view.View.VISIBLE; */ public abstract class BaseConfigurationWizard extends AppCompatActivity - implements NewProviderDialog.NewProviderDialogInterface, ProviderDetailFragment.ProviderDetailFragmentInterface, DownloadFailedDialog.DownloadFailedDialogInterface, ProviderAPIResultReceiver.Receiver { + implements NewProviderDialog.NewProviderDialogInterface, DownloadFailedDialog.DownloadFailedDialogInterface, ProviderAPIResultReceiver.Receiver { @InjectView(R.id.progressbar_configuration_wizard) protected ProgressBar mProgressBar; @InjectView(R.id.progressbar_description) @@ -150,22 +150,13 @@ public abstract class BaseConfigurationWizard extends AppCompatActivity private void restoreState(Bundle savedInstanceState) { progressbar_text = savedInstanceState.getString(PROGRESSBAR_TEXT, ""); selected_provider = savedInstanceState.getParcelable(Provider.KEY); - - if (fragment_manager.findFragmentByTag(ProviderDetailFragment.TAG) == null && - (SETTING_UP_PROVIDER.equals(mConfigState.getAction()) || - PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction()) || - PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction()) - )) { - onItemSelectedUi(); - } } @Override protected void onResume() { super.onResume(); if (SETTING_UP_PROVIDER.equals(mConfigState.getAction())) { - showProgressBar(); - adapter.hideAllBut(adapter.indexOf(selected_provider)); + cancelAndShowAllProviders(); } else if (PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction())) { showProviderDetails(); } else if (PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction())) { @@ -396,15 +387,9 @@ public abstract class BaseConfigurationWizard extends AppCompatActivity * */ public void showProviderDetails() { - try { - FragmentTransaction fragment_transaction = fragment_manager.removePreviousFragment(ProviderDetailFragment.TAG); - - DialogFragment newFragment = ProviderDetailFragment.newInstance(); - newFragment.show(fragment_transaction, ProviderDetailFragment.TAG); - } catch (IllegalStateException e) { - e.printStackTrace(); - mConfigState.setAction(PENDING_SHOW_PROVIDER_DETAILS); - } + Intent intent = new Intent(this, ProviderDetailActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + startActivity(intent); } @@ -428,32 +413,12 @@ public abstract class BaseConfigurationWizard extends AppCompatActivity } } - @Override public void cancelAndShowAllProviders() { mConfigState.setAction(PROVIDER_NOT_SET); selected_provider = null; adapter.showAllProviders(); } - @Override - public void login() { - mConfigState.setAction(PROVIDER_SET); - Intent ask_login = new Intent(); - ask_login.putExtra(Provider.KEY, selected_provider); - ask_login.putExtra(SessionDialog.TAG, SessionDialog.TAG); - setResult(RESULT_OK, ask_login); - finish(); - } - - @Override - public void use_anonymously() { - mConfigState.setAction(PROVIDER_SET); - Intent pass_provider = new Intent(); - pass_provider.putExtra(Provider.KEY, selected_provider); - setResult(RESULT_OK, pass_provider); - finish(); - } - public class ProviderAPIBroadcastReceiver_Update extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { -- cgit v1.2.3 From 8806e6ae477e0b20806851f5f8f3c0141a63ad9d Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 9 Jan 2018 19:54:57 +0100 Subject: create LoginActivity and SignUpActivity --- .../bitmaskclient/BaseConfigurationWizard.java | 3 +- .../se/leap/bitmaskclient/ButterKnifeActivity.java | 30 +++++ .../main/java/se/leap/bitmaskclient/Dashboard.java | 3 +- .../java/se/leap/bitmaskclient/LoginActivity.java | 29 +++++ .../ProviderCredentialsBaseActivity.java | 134 +++++++++++++++++++++ .../java/se/leap/bitmaskclient/SignupActivity.java | 66 ++++++++++ .../bitmaskclient/userstatus/SessionDialog.java | 6 +- .../userstatus/UserStatusFragment.java | 3 - 8 files changed, 264 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/ButterKnifeActivity.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/LoginActivity.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/ProviderCredentialsBaseActivity.java create mode 100644 app/src/main/java/se/leap/bitmaskclient/SignupActivity.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 601615b6..9253cfe6 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -69,7 +69,7 @@ import static android.view.View.VISIBLE; * @author cyberta */ -public abstract class BaseConfigurationWizard extends AppCompatActivity +public abstract class BaseConfigurationWizard extends ButterKnifeActivity implements NewProviderDialog.NewProviderDialogInterface, DownloadFailedDialog.DownloadFailedDialogInterface, ProviderAPIResultReceiver.Receiver { @InjectView(R.id.progressbar_configuration_wizard) protected ProgressBar mProgressBar; @@ -166,7 +166,6 @@ public abstract class BaseConfigurationWizard extends AppCompatActivity private void setUpInitialUI() { setContentView(R.layout.configuration_wizard_activity); - ButterKnife.inject(this); hideProgressBar(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/ButterKnifeActivity.java b/app/src/main/java/se/leap/bitmaskclient/ButterKnifeActivity.java new file mode 100644 index 00000000..41164463 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/ButterKnifeActivity.java @@ -0,0 +1,30 @@ +package se.leap.bitmaskclient; + +import android.support.v7.app.AppCompatActivity; +import android.view.View; + +import butterknife.ButterKnife; + +/** + * Automatically inject with ButterKnife after calling setContentView + */ + +public abstract class ButterKnifeActivity extends AppCompatActivity { + + @Override + public void setContentView(View view) { + super.setContentView(view); + ButterKnife.inject(this); + } + + @Override + public void setContentView(int layoutResID) { + super.setContentView(layoutResID); + ButterKnife.inject(this); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 8c33a6cd..b36c8cc2 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -57,7 +57,7 @@ import static se.leap.bitmaskclient.Constants.REQUEST_CODE_SWITCH_PROVIDER; * @author Sean Leonard * @author parmegv */ -public class Dashboard extends AppCompatActivity { +public class Dashboard extends ButterKnifeActivity { public static final String TAG = Dashboard.class.getSimpleName(); @@ -280,7 +280,6 @@ public class Dashboard extends AppCompatActivity { // just to start services and destroy them afterwards private void buildDashboard(boolean hideAndTurnOnEipOnBoot) { setContentView(R.layout.dashboard); - ButterKnife.inject(this); provider_name.setText(provider.getDomain()); diff --git a/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java b/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java new file mode 100644 index 00000000..1b36d807 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java @@ -0,0 +1,29 @@ +package se.leap.bitmaskclient; + +import android.os.Bundle; +import android.support.annotation.Nullable; + +import butterknife.OnClick; + +/** + * Created by fupduck on 09.01.18. + */ + +public class LoginActivity extends ProviderCredentialsBaseActivity { + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.a_login); + + setProviderHeaderText("providerNAME"); + setProviderHeaderLogo(R.drawable.mask); + } + + @Override + @OnClick(R.id.button) + void handleButton() { + login(getUsername(), getPassword()); + } + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderCredentialsBaseActivity.java b/app/src/main/java/se/leap/bitmaskclient/ProviderCredentialsBaseActivity.java new file mode 100644 index 00000000..c61b078f --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderCredentialsBaseActivity.java @@ -0,0 +1,134 @@ +package se.leap.bitmaskclient; + +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.support.annotation.DrawableRes; +import android.support.annotation.Nullable; +import android.support.annotation.StringRes; +import android.support.design.widget.TextInputEditText; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import butterknife.InjectView; +import butterknife.OnClick; +import se.leap.bitmaskclient.userstatus.SessionDialog; +import se.leap.bitmaskclient.userstatus.User; + +/** + * Created by fupduck on 09.01.18. + */ + +public abstract class ProviderCredentialsBaseActivity extends ButterKnifeActivity { + + protected ProviderAPIResultReceiver providerAPIResultReceiver; + + @InjectView(R.id.provider_header_logo) + ImageView providerHeaderLogo; + + @InjectView(R.id.provider_header_text) + TextView providerHeaderText; + + @InjectView(R.id.provider_credentials_username) + TextInputEditText providerCredentialsUsername; + + @InjectView(R.id.provider_credentials_password) + TextInputEditText providerCredentialsPassword; + + @InjectView(R.id.button) + Button providerCredentialsButton; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + providerAPIResultReceiver = new ProviderAPIResultReceiver(new Handler(), new ProviderCredentialsReceiver(this)); + + } + + @OnClick(R.id.button) + abstract void handleButton(); + + protected void setProviderHeaderLogo(@DrawableRes int providerHeaderLogo) { + this.providerHeaderLogo.setImageResource(providerHeaderLogo); + } + + protected void setProviderHeaderText(String providerHeaderText) { + this.providerHeaderText.setText(providerHeaderText); + } + + protected void setProviderHeaderText(@StringRes int providerHeaderText) { + this.providerHeaderText.setText(providerHeaderText); + } + + protected void setButtonText(@StringRes int buttonText) { + providerCredentialsButton.setText(buttonText); + } + + String getUsername() { + return providerCredentialsUsername.getText().toString(); + } + + String getPassword() { + return providerCredentialsPassword.getText().toString(); + } + + void login(String username, String password) { + User.setUserName(username); + Bundle parameters = bundlePassword(password); + ProviderAPICommand.execute(parameters, ProviderAPI.LOG_IN, providerAPIResultReceiver); + } + + public void signUp(String username, String password) { + User.setUserName(username); + Bundle parameters = bundlePassword(password); + ProviderAPICommand.execute(parameters, ProviderAPI.SIGN_UP, providerAPIResultReceiver); + } + protected Bundle bundlePassword(String password) { + Bundle parameters = new Bundle(); + if (!password.isEmpty()) + parameters.putString(SessionDialog.PASSWORD, password); + return parameters; + } + + public static class ProviderCredentialsReceiver implements ProviderAPIResultReceiver.Receiver{ + + private ProviderCredentialsBaseActivity activity; + + ProviderCredentialsReceiver(ProviderCredentialsBaseActivity activity) { + this.activity = activity; + } + + @Override + public void onReceiveResult(int resultCode, Bundle resultData) { + if (resultCode == ProviderAPI.SUCCESSFUL_SIGNUP) { + String username = resultData.getString(SessionDialog.USERNAME); + String password = resultData.getString(SessionDialog.PASSWORD); + activity.login(username, password); + } else if (resultCode == ProviderAPI.FAILED_SIGNUP) { + //MainActivity.sessionDialog(resultData); + } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGIN) { + Intent intent = new Intent(activity, MainActivity.class); + activity.startActivity(intent); + } else if (resultCode == ProviderAPI.FAILED_LOGIN) { + //MainActivity.sessionDialog(resultData); +// TODO MOVE +// } else if (resultCode == ProviderAPI.SUCCESSFUL_LOGOUT) { +// if (switching_provider) activity.switchProvider(); +// } else if (resultCode == ProviderAPI.LOGOUT_FAILED) { +// activity.setResult(RESULT_CANCELED); +// } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE) { +// activity.eip_fragment.updateEipService(); +// activity.setResult(RESULT_OK); +// } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE) { +// activity.setResult(RESULT_CANCELED); +// } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_EIP_SERVICE) { +// activity.eip_fragment.updateEipService(); +// activity.setResult(RESULT_OK); +// } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_EIP_SERVICE) { +// activity.setResult(RESULT_CANCELED); + } + } + } + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/SignupActivity.java b/app/src/main/java/se/leap/bitmaskclient/SignupActivity.java new file mode 100644 index 00000000..f6344065 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/SignupActivity.java @@ -0,0 +1,66 @@ +package se.leap.bitmaskclient; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.design.widget.TextInputEditText; +import android.support.design.widget.TextInputLayout; +import android.text.Editable; +import android.text.TextWatcher; + +import butterknife.InjectView; +import butterknife.OnClick; + +/** + * Create an account with a provider + */ + +public class SignupActivity extends ProviderCredentialsBaseActivity { + + @InjectView(R.id.provider_credentials_password_verification) + TextInputEditText providerCredentialsPasswordVerification; + + @InjectView(R.id.provider_credentials_password_verification_layout) + TextInputLayout providerCredentialsPasswordVerificationLayout; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.a_signup); + + setProviderHeaderText("providerNAME"); + setProviderHeaderLogo(R.drawable.mask); + + setButtonText(R.string.signup_button); + + providerCredentialsPasswordVerification.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void afterTextChanged(Editable s) { + if(getPassword().equals(getPasswordVerification())) { + providerCredentialsPasswordVerificationLayout.setError(null); + } else { + providerCredentialsPasswordVerificationLayout.setError(getString(R.string.password_mismatch)); + } + } + }); + } + + @Override + @OnClick(R.id.button) + void handleButton() { + if (getPassword().equals(getPasswordVerification())) { + signUp(getUsername(), getPassword()); + } + } + + private String getPasswordVerification() { + return providerCredentialsPasswordVerification.getText().toString(); + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java index 1256c619..d86da957 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java @@ -51,7 +51,7 @@ public class SessionDialog extends DialogFragment { final public static String USERNAME = "username"; final public static String PASSWORD = "password"; - public static enum ERRORS { + public enum ERRORS { USERNAME_MISSING, PASSWORD_INVALID_LENGTH, RISEUP_WARNING @@ -156,9 +156,9 @@ public class SessionDialog extends DialogFragment { * @author parmegv */ public interface SessionDialogInterface { - public void logIn(String username, String password); + void logIn(String username, String password); - public void signUp(String username, String password); + void signUp(String username, String password); } diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java index a6439a16..07c102e4 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java @@ -2,7 +2,6 @@ package se.leap.bitmaskclient.userstatus; import android.content.Context; import android.os.Bundle; -import android.os.Handler; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; @@ -18,7 +17,6 @@ import java.util.Observer; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; -import se.leap.bitmaskclient.Dashboard; import se.leap.bitmaskclient.MainActivity; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.ProviderAPI; @@ -74,7 +72,6 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia @Override public void onAttach(Context activity) { super.onAttach(activity); - providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), Dashboard.dashboardReceiver); } public void restoreSessionStatus(Bundle savedInstanceState) { -- cgit v1.2.3 From fba19da668411f722773617b2f09726701bc3ea8 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 11 Jan 2018 12:51:10 +0100 Subject: base class for production/insecure ProviderDetailActivity --- .../AbstractProviderDetailActivity.java | 116 +++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java b/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java new file mode 100644 index 00000000..6d69b71a --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java @@ -0,0 +1,116 @@ +package se.leap.bitmaskclient; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.util.Log; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.TextView; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + +import butterknife.InjectView; + +public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity { + + final public static String TAG = "providerDetailActivity"; + protected SharedPreferences preferences; + + @InjectView(R.id.provider_detail_domain) + TextView domain; + + @InjectView(R.id.provider_detail_name) + TextView name; + + @InjectView(R.id.provider_detail_description) + TextView description; + + @InjectView(R.id.provider_detail_options) + ListView options; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.provider_detail_fragment); + + preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + try { + JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); + domain.setText(provider_json.getString(Provider.DOMAIN)); + name.setText(provider_json.getJSONObject(Provider.NAME).getString("en")); + description.setText(provider_json.getJSONObject(Provider.DESCRIPTION).getString("en")); + + setTitle(R.string.provider_details_title); + + // Show only the options allowed by the provider + ArrayList optionsList = new ArrayList<>(); + if (registration_allowed(provider_json)) { + optionsList.add(getString(R.string.login_button)); + optionsList.add(getString(R.string.signup_button)); + } + if (anon_allowed(provider_json)) { + optionsList.add(getString(R.string.use_anonymously_button)); + } + + options.setAdapter(new ArrayAdapter<>( + this, + android.R.layout.simple_list_item_activated_1, + android.R.id.text1, + optionsList.toArray(new String[optionsList.size()]) + )); + options.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + String text = ((TextView) view).getText().toString(); + Intent intent; + if (text.equals(getString(R.string.login_button))) { + Log.d(TAG, "login selected"); + intent = new Intent(getApplicationContext(), LoginActivity.class); + } else if (text.equals(getString(R.string.signup_button))) { + Log.d(TAG, "signup selected"); + intent = new Intent(getApplicationContext(), SignupActivity.class); + } else { + intent = new Intent(getApplicationContext(), MainActivity.class); + } + intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + startActivity(intent); + } + }); + } catch (JSONException e) { + // TODO show error and return + } + } + + private boolean anon_allowed(JSONObject provider_json) { + try { + JSONObject service_description = provider_json.getJSONObject(Provider.SERVICE); + return service_description.has(Constants.PROVIDER_ALLOW_ANONYMOUS) && service_description.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS); + } catch (JSONException e) { + return false; + } + } + + private boolean registration_allowed(JSONObject provider_json) { + try { + JSONObject service_description = provider_json.getJSONObject(Provider.SERVICE); + return service_description.has(Provider.ALLOW_REGISTRATION) && service_description.getBoolean(Provider.ALLOW_REGISTRATION); + } catch (JSONException e) { + return false; + } + } + + @Override + public void onBackPressed() { + SharedPreferences.Editor editor = preferences.edit(); + editor.remove(Provider.KEY).remove(Constants.PROVIDER_ALLOW_ANONYMOUS).remove(Constants.PROVIDER_KEY).apply(); + super.onBackPressed(); + } + +} -- cgit v1.2.3 From 5d5d6ae8aeafbba407b9a4cf5985a1cdc1cf2904 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Thu, 11 Jan 2018 19:41:28 +0100 Subject: rename variables to CamelCase --- .../AbstractProviderDetailActivity.java | 25 ++--- .../bitmaskclient/BaseConfigurationWizard.java | 115 ++++++++++----------- .../main/java/se/leap/bitmaskclient/Dashboard.java | 2 +- .../bitmaskclient/FragmentManagerEnhanced.java | 20 ++-- .../java/se/leap/bitmaskclient/OnBootReceiver.java | 16 +-- .../se/leap/bitmaskclient/ProviderManager.java | 76 +++++++------- .../java/se/leap/bitmaskclient/VpnFragment.java | 91 ++++++++-------- .../main/java/se/leap/bitmaskclient/eip/EIP.java | 58 +++++------ .../leap/bitmaskclient/eip/VpnConfigGenerator.java | 64 ++++++------ .../bitmaskclient/userstatus/SessionDialog.java | 32 +++--- .../userstatus/UserStatusFragment.java | 8 +- 11 files changed, 252 insertions(+), 255 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java b/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java index 6d69b71a..c180e43a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java @@ -42,20 +42,20 @@ public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); try { - JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); - domain.setText(provider_json.getString(Provider.DOMAIN)); - name.setText(provider_json.getJSONObject(Provider.NAME).getString("en")); - description.setText(provider_json.getJSONObject(Provider.DESCRIPTION).getString("en")); + JSONObject providerJson = new JSONObject(preferences.getString(Provider.KEY, "")); + domain.setText(providerJson.getString(Provider.DOMAIN)); + name.setText(providerJson.getJSONObject(Provider.NAME).getString("en")); + description.setText(providerJson.getJSONObject(Provider.DESCRIPTION).getString("en")); setTitle(R.string.provider_details_title); // Show only the options allowed by the provider ArrayList optionsList = new ArrayList<>(); - if (registration_allowed(provider_json)) { + if (registrationAllowed(providerJson)) { optionsList.add(getString(R.string.login_button)); optionsList.add(getString(R.string.signup_button)); } - if (anon_allowed(provider_json)) { + if (anonAllowed(providerJson)) { optionsList.add(getString(R.string.use_anonymously_button)); } @@ -77,6 +77,7 @@ public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity Log.d(TAG, "signup selected"); intent = new Intent(getApplicationContext(), SignupActivity.class); } else { + Log.d(TAG, "use anonymously selected"); intent = new Intent(getApplicationContext(), MainActivity.class); } intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); @@ -88,19 +89,19 @@ public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity } } - private boolean anon_allowed(JSONObject provider_json) { + private boolean anonAllowed(JSONObject providerJson) { try { - JSONObject service_description = provider_json.getJSONObject(Provider.SERVICE); - return service_description.has(Constants.PROVIDER_ALLOW_ANONYMOUS) && service_description.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS); + JSONObject serviceDescription = providerJson.getJSONObject(Provider.SERVICE); + return serviceDescription.has(Constants.PROVIDER_ALLOW_ANONYMOUS) && serviceDescription.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS); } catch (JSONException e) { return false; } } - private boolean registration_allowed(JSONObject provider_json) { + private boolean registrationAllowed(JSONObject providerJson) { try { - JSONObject service_description = provider_json.getJSONObject(Provider.SERVICE); - return service_description.has(Provider.ALLOW_REGISTRATION) && service_description.getBoolean(Provider.ALLOW_REGISTRATION); + JSONObject serviceDescription = providerJson.getJSONObject(Provider.SERVICE); + return serviceDescription.has(Provider.ALLOW_REGISTRATION) && serviceDescription.getBoolean(Provider.ALLOW_REGISTRATION); } catch (JSONException e) { return false; } diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 0b51af27..915e948a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -26,7 +26,6 @@ import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentTransaction; -import android.support.v7.app.AppCompatActivity; import android.view.Display; import android.view.Menu; import android.view.MenuItem; @@ -48,11 +47,9 @@ import java.util.List; import javax.inject.Inject; -import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnItemClick; import se.leap.bitmaskclient.fragments.AboutFragment; -import se.leap.bitmaskclient.userstatus.SessionDialog; import static android.view.View.GONE; import static android.view.View.INVISIBLE; @@ -75,16 +72,16 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity @InjectView(R.id.progressbar_configuration_wizard) protected ProgressBar mProgressBar; @InjectView(R.id.progressbar_description) - protected TextView progressbar_description; + protected TextView progressbarDescription; @InjectView(R.id.provider_list) - protected ListView provider_list_view; + protected ListView providerListView; @Inject protected ProviderListAdapter adapter; - private ProviderManager provider_manager; + private ProviderManager providerManager; protected Intent mConfigState = new Intent(PROVIDER_NOT_SET); - protected Provider selected_provider; + protected Provider selectedProvider; final public static String TAG = ConfigurationWizard.class.getSimpleName(); @@ -99,13 +96,13 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity final private static String PROGRESSBAR_TEXT = TAG + "PROGRESSBAR_TEXT"; final private static String PROGRESSBAR_NUMBER = TAG + "PROGRESSBAR_NUMBER"; - public ProviderAPIResultReceiver providerAPI_result_receiver; - private ProviderAPIBroadcastReceiver_Update providerAPI_broadcast_receiver_update; + public ProviderAPIResultReceiver providerAPIResultReceiver; + private BaseConfigurationWizard.providerAPIBroadcastReceiverUpdate providerAPIBroadcastReceiverUpdate; protected static SharedPreferences preferences; - FragmentManagerEnhanced fragment_manager; - //TODO: add some states (values for progressbar_text) about ongoing setup or remove that field - private String progressbar_text = ""; + FragmentManagerEnhanced fragmentManager; + //TODO: add some states (values for progressbarText) about ongoing setup or remove that field + private String progressbarText = ""; @@ -118,17 +115,17 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity List> prototypes = new ArrayList<>(); prototypes.add(new ProviderRenderer(this)); ProviderRendererBuilder providerRendererBuilder = new ProviderRendererBuilder(prototypes); - adapter = new ProviderListAdapter(getLayoutInflater(), providerRendererBuilder, provider_manager); - provider_list_view.setAdapter(adapter); + adapter = new ProviderListAdapter(getLayoutInflater(), providerRendererBuilder, providerManager); + providerListView.setAdapter(adapter); } @Override protected void onSaveInstanceState(@NotNull Bundle outState) { if (mProgressBar != null) outState.putInt(PROGRESSBAR_NUMBER, mProgressBar.getProgress()); - if (progressbar_description != null) - outState.putString(PROGRESSBAR_TEXT, progressbar_description.getText().toString()); - outState.putParcelable(Provider.KEY, selected_provider); + if (progressbarDescription != null) + outState.putString(PROGRESSBAR_TEXT, progressbarDescription.getText().toString()); + outState.putParcelable(Provider.KEY, selectedProvider); super.onSaveInstanceState(outState); } @@ -136,8 +133,8 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); - fragment_manager = new FragmentManagerEnhanced(getSupportFragmentManager()); - provider_manager = ProviderManager.getInstance(getAssets(), getExternalFilesDir(null)); + fragmentManager = new FragmentManagerEnhanced(getSupportFragmentManager()); + providerManager = ProviderManager.getInstance(getAssets(), getExternalFilesDir(null)); setUpInitialUI(); @@ -149,8 +146,8 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity } private void restoreState(Bundle savedInstanceState) { - progressbar_text = savedInstanceState.getString(PROGRESSBAR_TEXT, ""); - selected_provider = savedInstanceState.getParcelable(Provider.KEY); + progressbarText = savedInstanceState.getString(PROGRESSBAR_TEXT, ""); + selectedProvider = savedInstanceState.getParcelable(Provider.KEY); } @Override @@ -172,43 +169,43 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity } private void hideProgressBar() { - //needs to be "INVISIBLE" instead of GONE b/c the progressbar_description gets translated + //needs to be "INVISIBLE" instead of GONE b/c the progressbarDescription gets translated // by the height of mProgressbar (and the height of the first list item) mProgressBar.setVisibility(INVISIBLE); - progressbar_description.setVisibility(INVISIBLE); + progressbarDescription.setVisibility(INVISIBLE); mProgressBar.setProgress(0); } protected void showProgressBar() { mProgressBar.setVisibility(VISIBLE); - progressbar_description.setVisibility(VISIBLE); + progressbarDescription.setVisibility(VISIBLE); } @Override protected void onDestroy() { super.onDestroy(); - if (providerAPI_broadcast_receiver_update != null) - unregisterReceiver(providerAPI_broadcast_receiver_update); + if (providerAPIBroadcastReceiverUpdate != null) + unregisterReceiver(providerAPIBroadcastReceiverUpdate); } private void setUpProviderAPIResultReceiver() { - providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), this); - providerAPI_broadcast_receiver_update = new ProviderAPIBroadcastReceiver_Update(); + providerAPIResultReceiver = new ProviderAPIResultReceiver(new Handler(), this); + providerAPIBroadcastReceiverUpdate = new providerAPIBroadcastReceiverUpdate(); IntentFilter update_intent_filter = new IntentFilter(ProviderAPI.UPDATE_PROGRESSBAR); update_intent_filter.addCategory(Intent.CATEGORY_DEFAULT); - registerReceiver(providerAPI_broadcast_receiver_update, update_intent_filter); + registerReceiver(providerAPIBroadcastReceiverUpdate, update_intent_filter); } @Override public void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode == ProviderAPI.PROVIDER_OK) { try { - String provider_json_string = preferences.getString(Provider.KEY, ""); - if (!provider_json_string.isEmpty()) - selected_provider.define(new JSONObject(provider_json_string)); + String providerJsonString = preferences.getString(Provider.KEY, ""); + if (!providerJsonString.isEmpty()) + selectedProvider.define(new JSONObject(providerJsonString)); String caCert = preferences.getString(Provider.CA_CERT, ""); - selected_provider.setCACert(caCert); + selectedProvider.setCACert(caCert); } catch (JSONException e) { e.printStackTrace(); } @@ -255,13 +252,13 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity //TODO Code 2 pane view mConfigState.setAction(SETTING_UP_PROVIDER); - selected_provider = adapter.getItem(position); + selectedProvider = adapter.getItem(position); onItemSelectedUi(); onItemSelectedLogic(); } protected void onItemSelectedUi() { - adapter.hideAllBut(adapter.indexOf(selected_provider)); + adapter.hideAllBut(adapter.indexOf(selectedProvider)); startProgressBar(); } @@ -281,7 +278,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity ProviderAPI.stop(); mProgressBar.setVisibility(GONE); mProgressBar.setProgress(0); - progressbar_description.setVisibility(GONE); + progressbarDescription.setVisibility(GONE); cancelSettingUpProvider(); } @@ -297,21 +294,21 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity @Override public void updateProviderDetails() { mConfigState.setAction(SETTING_UP_PROVIDER); - Intent provider_API_command = new Intent(this, ProviderAPI.class); + Intent providerAPICommand = new Intent(this, ProviderAPI.class); - provider_API_command.setAction(ProviderAPI.UPDATE_PROVIDER_DETAILS); - provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, providerAPI_result_receiver); + providerAPICommand.setAction(ProviderAPI.UPDATE_PROVIDER_DETAILS); + providerAPICommand.putExtra(ProviderAPI.RECEIVER_KEY, providerAPIResultReceiver); Bundle parameters = new Bundle(); - parameters.putString(Provider.MAIN_URL, selected_provider.getMainUrl().toString()); - provider_API_command.putExtra(ProviderAPI.PARAMETERS, parameters); + parameters.putString(Provider.MAIN_URL, selectedProvider.getMainUrl().toString()); + providerAPICommand.putExtra(ProviderAPI.PARAMETERS, parameters); - startService(provider_API_command); + startService(providerAPICommand); } private void askDashboardToQuitApp() { - Intent ask_quit = new Intent(); - ask_quit.putExtra(Constants.APP_ACTION_QUIT, Constants.APP_ACTION_QUIT); - setResult(RESULT_CANCELED, ask_quit); + Intent askQuit = new Intent(); + askQuit.putExtra(Constants.APP_ACTION_QUIT, Constants.APP_ACTION_QUIT); + setResult(RESULT_CANCELED, askQuit); } private void startProgressBar() { @@ -321,11 +318,11 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity int measured_height = listItemHeight(); mProgressBar.setTranslationY(measured_height); - progressbar_description.setTranslationY(measured_height + mProgressBar.getHeight()); + progressbarDescription.setTranslationY(measured_height + mProgressBar.getHeight()); } private int listItemHeight() { - View listItem = adapter.getView(0, null, provider_list_view); + View listItem = adapter.getView(0, null, providerListView); listItem.setLayoutParams(new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); @@ -346,33 +343,33 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity * Asks ProviderApiService to download an anonymous (anon) VPN certificate. */ private void downloadVpnCertificate() { - Intent provider_API_command = new Intent(this, ProviderAPI.class); + Intent providerAPICommand = new Intent(this, ProviderAPI.class); - provider_API_command.setAction(ProviderAPI.DOWNLOAD_CERTIFICATE); - provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, providerAPI_result_receiver); + providerAPICommand.setAction(ProviderAPI.DOWNLOAD_CERTIFICATE); + providerAPICommand.putExtra(ProviderAPI.RECEIVER_KEY, providerAPIResultReceiver); - startService(provider_API_command); + startService(providerAPICommand); } /** * Open the new provider dialog */ public void addAndSelectNewProvider() { - FragmentTransaction fragment_transaction = fragment_manager.removePreviousFragment(NewProviderDialog.TAG); - new NewProviderDialog().show(fragment_transaction, NewProviderDialog.TAG); + FragmentTransaction fragmentTransaction = fragmentManager.removePreviousFragment(NewProviderDialog.TAG); + new NewProviderDialog().show(fragmentTransaction, NewProviderDialog.TAG); } /** * Open the new provider dialog with data */ public void addAndSelectNewProvider(String main_url) { - FragmentTransaction fragment_transaction = fragment_manager.removePreviousFragment(NewProviderDialog.TAG); + FragmentTransaction fragmentTransaction = fragmentManager.removePreviousFragment(NewProviderDialog.TAG); DialogFragment newFragment = new NewProviderDialog(); Bundle data = new Bundle(); data.putString(Provider.MAIN_URL, main_url); newFragment.setArguments(data); - newFragment.show(fragment_transaction, NewProviderDialog.TAG); + newFragment.show(fragmentTransaction, NewProviderDialog.TAG); } /** @@ -382,7 +379,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity */ public void showDownloadFailedDialog(String reasonToFail) { try { - FragmentTransaction fragment_transaction = fragment_manager.removePreviousFragment(DownloadFailedDialog.TAG); + FragmentTransaction fragmentTransaction = fragmentManager.removePreviousFragment(DownloadFailedDialog.TAG); DialogFragment newFragment; try { JSONObject errorJson = new JSONObject(reasonToFail); @@ -391,7 +388,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity e.printStackTrace(); newFragment = DownloadFailedDialog.newInstance(reasonToFail); } - newFragment.show(fragment_transaction, DownloadFailedDialog.TAG); + newFragment.show(fragmentTransaction, DownloadFailedDialog.TAG); } catch (IllegalStateException e) { e.printStackTrace(); mConfigState.setAction(PENDING_SHOW_FAILED_DIALOG); @@ -435,11 +432,11 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity public void cancelAndShowAllProviders() { mConfigState.setAction(PROVIDER_NOT_SET); - selected_provider = null; + selectedProvider = null; adapter.showAllProviders(); } - public class ProviderAPIBroadcastReceiver_Update extends BroadcastReceiver { + public class providerAPIBroadcastReceiverUpdate extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int update = intent.getIntExtra(ProviderAPI.CURRENT_PROGRESS, 0); diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index dc58b865..3e8668de 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -283,7 +283,7 @@ public class Dashboard extends ButterKnifeActivity { * service dependent UI elements to include. */ //TODO: REFACTOR ME! Consider implementing a manager that handles most of VpnFragment's logic about handling EIP commands. - //This way, we could avoid to create UI elements (like fragment_manager.replace(R.id.servicesCollection, eip_fragment, VpnFragment.TAG); ) + //This way, we could avoid to create UI elements (like fragmentManager.replace(R.id.servicesCollection, eip_fragment, VpnFragment.TAG); ) // just to start services and destroy them afterwards private void buildDashboard(boolean hideAndTurnOnEipOnBoot) { setContentView(R.layout.dashboard); diff --git a/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java b/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java index 9594cea0..9fe4fd23 100644 --- a/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java +++ b/app/src/main/java/se/leap/bitmaskclient/FragmentManagerEnhanced.java @@ -22,17 +22,17 @@ import android.support.v4.app.FragmentTransaction; public class FragmentManagerEnhanced { - private FragmentManager generic_fragment_manager; + private FragmentManager genericFragmentManager; - public FragmentManagerEnhanced(FragmentManager generic_fragment_manager) { - this.generic_fragment_manager = generic_fragment_manager; + public FragmentManagerEnhanced(FragmentManager genericFragmentManager) { + this.genericFragmentManager = genericFragmentManager; } public FragmentTransaction removePreviousFragment(String tag) { - FragmentTransaction transaction = generic_fragment_manager.beginTransaction(); - Fragment previous_fragment = generic_fragment_manager.findFragmentByTag(tag); - if (previous_fragment != null) { - transaction.remove(previous_fragment); + FragmentTransaction transaction = genericFragmentManager.beginTransaction(); + Fragment previousFragment = genericFragmentManager.findFragmentByTag(tag); + if (previousFragment != null) { + transaction.remove(previousFragment); } transaction.addToBackStack(null); @@ -40,16 +40,16 @@ public class FragmentManagerEnhanced { } public void replace(int containerViewId, Fragment fragment, String tag) { - FragmentTransaction transaction = generic_fragment_manager.beginTransaction(); + FragmentTransaction transaction = genericFragmentManager.beginTransaction(); transaction.replace(containerViewId, fragment, tag).commit(); } public FragmentTransaction beginTransaction() { - return generic_fragment_manager.beginTransaction(); + return genericFragmentManager.beginTransaction(); } public Fragment findFragmentByTag(String tag) { - return generic_fragment_manager.findFragmentByTag(tag); + return genericFragmentManager.findFragmentByTag(tag); } } diff --git a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java index a87e0460..aa661723 100644 --- a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java +++ b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java @@ -33,17 +33,17 @@ public class OnBootReceiver extends BroadcastReceiver { return; } if (startOnBoot) { - Intent dashboard_intent = new Intent(context, Dashboard.class); - dashboard_intent.putExtra(EIP_RESTART_ON_BOOT, true); - dashboard_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(dashboard_intent); + Intent dashboardIntent = new Intent(context, Dashboard.class); + dashboardIntent.putExtra(EIP_RESTART_ON_BOOT, true); + dashboardIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(dashboardIntent); } } else { if (isAlwaysOnConfigured) { - Intent dashboard_intent = new Intent(context, Dashboard.class); - dashboard_intent.putExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE, true); - dashboard_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(dashboard_intent); + Intent dashboardIntent = new Intent(context, Dashboard.class); + dashboardIntent.putExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE, true); + dashboardIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(dashboardIntent); } } } diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderManager.java b/app/src/main/java/se/leap/bitmaskclient/ProviderManager.java index 92d5da9f..62c04c1a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderManager.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderManager.java @@ -27,39 +27,39 @@ public class ProviderManager implements AdapteeCollection { private static final String TAG = ProviderManager.class.getName(); private AssetManager assets_manager; - private File external_files_dir; - private Set default_providers; - private Set custom_providers; + private File externalFilesDir; + private Set defaultProviders; + private Set customProviders; private static ProviderManager instance; final protected static String URLS = "urls"; - public static ProviderManager getInstance(AssetManager assets_manager, File external_files_dir) { + public static ProviderManager getInstance(AssetManager assetsManager, File externalFilesDir) { if (instance == null) - instance = new ProviderManager(assets_manager, external_files_dir); + instance = new ProviderManager(assetsManager, externalFilesDir); return instance; } - public ProviderManager(AssetManager assets_manager, File external_files_dir) { - this.assets_manager = assets_manager; - addDefaultProviders(assets_manager); - addCustomProviders(external_files_dir); + public ProviderManager(AssetManager assetManager, File externalFilesDir) { + this.assets_manager = assetManager; + addDefaultProviders(assetManager); + addCustomProviders(externalFilesDir); } private void addDefaultProviders(AssetManager assets_manager) { try { - default_providers = providersFromAssets(URLS, assets_manager.list(URLS)); + defaultProviders = providersFromAssets(URLS, assets_manager.list(URLS)); } catch (IOException e) { e.printStackTrace(); } } - private Set providersFromAssets(String directory, String[] relative_file_paths) { + private Set providersFromAssets(String directory, String[] relativeFilePaths) { Set providers = new HashSet(); - for (String file : relative_file_paths) { + for (String file : relativeFilePaths) { String mainUrl = null; String certificate = null; String providerDefinition = null; @@ -83,10 +83,10 @@ public class ProviderManager implements AdapteeCollection { } - private void addCustomProviders(File external_files_dir) { - this.external_files_dir = external_files_dir; - custom_providers = external_files_dir != null && external_files_dir.isDirectory() ? - providersFromFiles(external_files_dir.list()) : + private void addCustomProviders(File externalFilesDir) { + this.externalFilesDir = externalFilesDir; + customProviders = externalFilesDir != null && externalFilesDir.isDirectory() ? + providersFromFiles(externalFilesDir.list()) : new HashSet(); } @@ -94,7 +94,7 @@ public class ProviderManager implements AdapteeCollection { Set providers = new HashSet(); try { for (String file : files) { - String main_url = extractMainUrlFromInputStream(new FileInputStream(external_files_dir.getAbsolutePath() + "/" + file)); + String main_url = extractMainUrlFromInputStream(new FileInputStream(externalFilesDir.getAbsolutePath() + "/" + file)); providers.add(new Provider(new URL(main_url))); } } catch (MalformedURLException | FileNotFoundException e) { @@ -105,21 +105,21 @@ public class ProviderManager implements AdapteeCollection { } private String extractMainUrlFromInputStream(InputStream input_stream) { - String main_url = ""; + String mainUrl = ""; JSONObject file_contents = inputStreamToJson(input_stream); if (file_contents != null) - main_url = file_contents.optString(Provider.MAIN_URL); - return main_url; + mainUrl = file_contents.optString(Provider.MAIN_URL); + return mainUrl; } - private JSONObject inputStreamToJson(InputStream input_stream) { + private JSONObject inputStreamToJson(InputStream inputStream) { JSONObject json = null; try { - byte[] bytes = new byte[input_stream.available()]; - if (input_stream.read(bytes) > 0) + byte[] bytes = new byte[inputStream.available()]; + if (inputStream.read(bytes) > 0) json = new JSONObject(new String(bytes)); - input_stream.reset(); + inputStream.reset(); } catch (IOException | JSONException e) { e.printStackTrace(); } @@ -128,9 +128,9 @@ public class ProviderManager implements AdapteeCollection { public Set providers() { Set all_providers = new HashSet(); - all_providers.addAll(default_providers); - if(custom_providers != null) - all_providers.addAll(custom_providers); + all_providers.addAll(defaultProviders); + if(customProviders != null) + all_providers.addAll(customProviders); return all_providers; } @@ -151,40 +151,40 @@ public class ProviderManager implements AdapteeCollection { @Override public boolean add(Provider element) { - if (!default_providers.contains(element)) - return custom_providers.add(element); + if (!defaultProviders.contains(element)) + return customProviders.add(element); else return true; } @Override public boolean remove(Object element) { - return custom_providers.remove(element); + return customProviders.remove(element); } @Override public boolean addAll(Collection elements) { - return custom_providers.addAll(elements); + return customProviders.addAll(elements); } @Override public boolean removeAll(Collection elements) { if(!elements.getClass().equals(Provider.class)) return false; - return default_providers.removeAll(elements) || custom_providers.removeAll(elements); + return defaultProviders.removeAll(elements) || customProviders.removeAll(elements); } @Override public void clear() { - default_providers.clear(); - custom_providers.clear(); + defaultProviders.clear(); + customProviders.clear(); } protected void saveCustomProvidersToFile() { try { - for (Provider provider : custom_providers) { - File provider_file = new File(external_files_dir, provider.getName() + ".json"); - if (!provider_file.exists()) { - FileWriter writer = new FileWriter(provider_file); + for (Provider provider : customProviders) { + File providerFile = new File(externalFilesDir, provider.getName() + ".json"); + if (!providerFile.exists()) { + FileWriter writer = new FileWriter(providerFile); writer.write(provider.toJson().toString()); writer.close(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index e16ab75c..0af23917 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -76,13 +76,13 @@ public class VpnFragment extends Fragment implements Observer { private SharedPreferences preferences; @InjectView(R.id.vpn_status_image) - FabButton vpn_status_image; + FabButton vpnStatusImage; @InjectView(R.id.vpn_main_button) - Button main_button; + Button mainButton; - private static EIPReceiver eip_receiver; - private static EipStatus eip_status; - private boolean wants_to_connect; + private static EIPReceiver eipReceiver; + private static EipStatus eipStatus; + private boolean wantsToConnect; private IOpenVPNServiceInternal mService; private ServiceConnection openVpnConnection = new ServiceConnection() { @@ -103,18 +103,17 @@ public class VpnFragment extends Fragment implements Observer { }; - //FIXME: replace with onAttach(Context context) - public void onAttach(Activity activity) { - super.onAttach(activity); + public void onAttach(Context context) { + super.onAttach(context); downloadEIPServiceConfig(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - eip_status = EipStatus.getInstance(); - eip_status.addObserver(this); - eip_receiver = new EIPReceiver(new Handler()); + eipStatus = EipStatus.getInstance(); + eipStatus.addObserver(this); + eipReceiver = new EIPReceiver(new Handler()); preferences = getActivity().getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); } @@ -147,7 +146,7 @@ public class VpnFragment extends Fragment implements Observer { @Override public void onSaveInstanceState(Bundle outState) { - outState.putBoolean(IS_CONNECTED, eip_status.isConnected()); + outState.putBoolean(IS_CONNECTED, eipStatus.isConnected()); super.onSaveInstanceState(outState); } @@ -157,7 +156,7 @@ public class VpnFragment extends Fragment implements Observer { @OnClick(R.id.vpn_main_button) void handleIcon() { - if (eip_status.isConnected() || eip_status.isConnecting()) + if (eipStatus.isConnected() || eipStatus.isConnecting()) handleSwitchOff(); else handleSwitchOn(); @@ -167,7 +166,7 @@ public class VpnFragment extends Fragment implements Observer { if (canStartEIP()) startEipFromScratch(); else if (canLogInToStartEIP()) { - wants_to_connect = true; + wantsToConnect = true; Bundle bundle = new Bundle(); MainActivity.sessionDialog(bundle); } else { @@ -180,19 +179,19 @@ public class VpnFragment extends Fragment implements Observer { private boolean canStartEIP() { boolean certificateExists = !preferences.getString(PROVIDER_VPN_CERTIFICATE, "").isEmpty(); boolean isAllowedAnon = preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false); - return (isAllowedAnon || certificateExists) && !eip_status.isConnected() && !eip_status.isConnecting(); + return (isAllowedAnon || certificateExists) && !eipStatus.isConnected() && !eipStatus.isConnecting(); } private boolean canLogInToStartEIP() { boolean isAllowedRegistered = preferences.getBoolean(PROVIDER_ALLOWED_REGISTERED, false); boolean isLoggedIn = !LeapSRPSession.getToken().isEmpty(); - return isAllowedRegistered && !isLoggedIn && !eip_status.isConnecting() && !eip_status.isConnected(); + return isAllowedRegistered && !isLoggedIn && !eipStatus.isConnecting() && !eipStatus.isConnected(); } private void handleSwitchOff() { - if (eip_status.isConnecting()) { + if (eipStatus.isConnecting()) { askPendingStartCancellation(); - } else if (eip_status.isConnected()) { + } else if (eipStatus.isConnected()) { askToStopEIP(); } else { updateIcon(); @@ -219,14 +218,14 @@ public class VpnFragment extends Fragment implements Observer { } public void startEipFromScratch() { - wants_to_connect = false; + wantsToConnect = false; saveStatus(true); eipCommand(EIP_ACTION_START); } private void stop() { saveStatus(false); - if (eip_status.isBlockingVpnEstablished()) { + if (eipStatus.isBlockingVpnEstablished()) { stopBlockingVpn(); } disconnect(); @@ -258,7 +257,7 @@ public class VpnFragment extends Fragment implements Observer { private void downloadEIPServiceConfig() { ProviderAPIResultReceiver provider_api_receiver = new ProviderAPIResultReceiver(new Handler(), Dashboard.dashboardReceiver); - if(eip_receiver != null) + if(eipReceiver != null) ProviderAPICommand.execute(Bundle.EMPTY, ProviderAPI.DOWNLOAD_EIP_SERVICE, provider_api_receiver); } @@ -296,14 +295,14 @@ public class VpnFragment extends Fragment implements Observer { // TODO validate "action"...how do we get the list of intent-filters for a class via Android API? Intent vpn_intent = new Intent(activity.getApplicationContext(), EIP.class); vpn_intent.setAction(action); - vpn_intent.putExtra(EIP_RECEIVER, eip_receiver); + vpn_intent.putExtra(EIP_RECEIVER, eipReceiver); activity.startService(vpn_intent); } @Override public void update(Observable observable, Object data) { if (observable instanceof EipStatus) { - eip_status = (EipStatus) observable; + eipStatus = (EipStatus) observable; Activity activity = getActivity(); if (activity != null) { getActivity().runOnUiThread(new Runnable() { @@ -324,40 +323,40 @@ public class VpnFragment extends Fragment implements Observer { } private void updateIcon() { - if (eip_status.isBlocking()) { - vpn_status_image.showProgress(false); - vpn_status_image.setIcon(R.drawable.ic_stat_vpn_blocking, R.drawable.ic_stat_vpn_blocking); - vpn_status_image.setTag(R.drawable.ic_stat_vpn_blocking); - } else if (eip_status.isConnecting()) { - vpn_status_image.showProgress(true); - vpn_status_image.setIcon(R.drawable.ic_stat_vpn_empty_halo, R.drawable.ic_stat_vpn_empty_halo); - vpn_status_image.setTag(R.drawable.ic_stat_vpn_empty_halo); - } else if (eip_status.isConnected()){ - vpn_status_image.showProgress(false); - vpn_status_image.setIcon(R.drawable.ic_stat_vpn, R.drawable.ic_stat_vpn); - vpn_status_image.setTag(R.drawable.ic_stat_vpn); + if (eipStatus.isBlocking()) { + vpnStatusImage.showProgress(false); + vpnStatusImage.setIcon(R.drawable.ic_stat_vpn_blocking, R.drawable.ic_stat_vpn_blocking); + vpnStatusImage.setTag(R.drawable.ic_stat_vpn_blocking); + } else if (eipStatus.isConnecting()) { + vpnStatusImage.showProgress(true); + vpnStatusImage.setIcon(R.drawable.ic_stat_vpn_empty_halo, R.drawable.ic_stat_vpn_empty_halo); + vpnStatusImage.setTag(R.drawable.ic_stat_vpn_empty_halo); + } else if (eipStatus.isConnected()){ + vpnStatusImage.showProgress(false); + vpnStatusImage.setIcon(R.drawable.ic_stat_vpn, R.drawable.ic_stat_vpn); + vpnStatusImage.setTag(R.drawable.ic_stat_vpn); } else { - vpn_status_image.setIcon(R.drawable.ic_stat_vpn_offline, R.drawable.ic_stat_vpn_offline); - vpn_status_image.setTag(R.drawable.ic_stat_vpn_offline); - vpn_status_image.showProgress(false); + vpnStatusImage.setIcon(R.drawable.ic_stat_vpn_offline, R.drawable.ic_stat_vpn_offline); + vpnStatusImage.setTag(R.drawable.ic_stat_vpn_offline); + vpnStatusImage.showProgress(false); } } private void updateButton() { Activity activity = getActivity(); - if (eip_status.isConnecting()) { - main_button.setText(activity.getString(android.R.string.cancel)); - } else if (eip_status.isConnected() || isOpenVpnRunningWithoutNetwork()) { - main_button.setText(activity.getString(R.string.vpn_button_turn_off)); + if (eipStatus.isConnecting()) { + mainButton.setText(activity.getString(android.R.string.cancel)); + } else if (eipStatus.isConnected() || isOpenVpnRunningWithoutNetwork()) { + mainButton.setText(activity.getString(R.string.vpn_button_turn_off)); } else { - main_button.setText(activity.getString(R.string.vpn_button_turn_on)); + mainButton.setText(activity.getString(R.string.vpn_button_turn_on)); } } private boolean isOpenVpnRunningWithoutNetwork() { boolean isRunning = false; try { - isRunning = eip_status.getLevel() == LEVEL_NONETWORK && + isRunning = eipStatus.getLevel() == LEVEL_NONETWORK && mService.isVpnRunning(); } catch (Exception e) { //eat me @@ -428,7 +427,7 @@ public class VpnFragment extends Fragment implements Observer { case EIP_ACTION_UPDATE: switch (resultCode) { case Activity.RESULT_OK: - if (wants_to_connect) + if (wantsToConnect) startEipFromScratch(); break; case Activity.RESULT_CANCELED: @@ -441,6 +440,6 @@ public class VpnFragment extends Fragment implements Observer { public static EIPReceiver getReceiver() { - return eip_receiver; + return eipReceiver; } } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java index 998d2c87..a2ac9d66 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java @@ -63,8 +63,8 @@ public final class EIP extends IntentService { private static ResultReceiver mReceiver; private static SharedPreferences preferences; - private static JSONObject eip_definition; - private static GatewaysManager gateways_manager = new GatewaysManager(); + private static JSONObject eipDefinition; + private static GatewaysManager gatewaysManager = new GatewaysManager(); private static Gateway gateway; public EIP() { @@ -76,8 +76,8 @@ public final class EIP extends IntentService { super.onCreate(); context = getApplicationContext(); preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); - eip_definition = eipDefinitionFromPreferences(); - if (gateways_manager.isEmpty()) + eipDefinition = eipDefinitionFromPreferences(); + if (gatewaysManager.isEmpty()) gatewaysFromPreferences(); } @@ -106,13 +106,13 @@ public final class EIP extends IntentService { * It also sets up early routes. */ private void startEIP() { - if (gateways_manager.isEmpty()) + if (gatewaysManager.isEmpty()) updateEIPService(); if (!EipStatus.getInstance().isBlockingVpnEstablished()) { earlyRoutes(); } - gateway = gateways_manager.select(); + gateway = gatewaysManager.select(); if (gateway != null && gateway.getProfile() != null) { mReceiver = VpnFragment.getReceiver(); launchActiveGateway(); @@ -128,10 +128,10 @@ public final class EIP extends IntentService { private void startAlwaysOnEIP() { Log.d(TAG, "startAlwaysOnEIP vpn"); - if (gateways_manager.isEmpty()) + if (gatewaysManager.isEmpty()) updateEIPService(); - gateway = gateways_manager.select(); + gateway = gatewaysManager.select(); if (gateway != null && gateway.getProfile() != null) { //mReceiver = VpnFragment.getReceiver(); @@ -147,9 +147,9 @@ public final class EIP extends IntentService { * VpnService is started properly. */ private void earlyRoutes() { - Intent void_vpn_launcher = new Intent(context, VoidVpnLauncher.class); - void_vpn_launcher.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(void_vpn_launcher); + Intent voidVpnLauncher = new Intent(context, VoidVpnLauncher.class); + voidVpnLauncher.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(voidVpnLauncher); } private void launchActiveGateway() { @@ -162,12 +162,12 @@ public final class EIP extends IntentService { } private void stopEIP() { - EipStatus eip_status = EipStatus.getInstance(); - int result_code = Activity.RESULT_CANCELED; - if (eip_status.isConnected() || eip_status.isConnecting()) - result_code = Activity.RESULT_OK; + EipStatus eipStatus = EipStatus.getInstance(); + int resultCode = Activity.RESULT_CANCELED; + if (eipStatus.isConnected() || eipStatus.isConnecting()) + resultCode = Activity.RESULT_OK; - tellToReceiver(EIP_ACTION_STOP, result_code); + tellToReceiver(EIP_ACTION_STOP, resultCode); } /** @@ -176,8 +176,8 @@ public final class EIP extends IntentService { * request if it's not connected, Activity.RESULT_OK otherwise. */ private void isRunning() { - EipStatus eip_status = EipStatus.getInstance(); - int resultCode = (eip_status.isConnected()) ? + EipStatus eipStatus = EipStatus.getInstance(); + int resultCode = (eipStatus.isConnected()) ? Activity.RESULT_OK : Activity.RESULT_CANCELED; tellToReceiver(EIP_ACTION_IS_RUNNING, resultCode); @@ -188,8 +188,8 @@ public final class EIP extends IntentService { * TODO Implement API call to refresh eip-service.json from the provider */ private void updateEIPService() { - eip_definition = eipDefinitionFromPreferences(); - if (eip_definition.length() > 0) + eipDefinition = eipDefinitionFromPreferences(); + if (eipDefinition.length() > 0) updateGateways(); tellToReceiver(EIP_ACTION_UPDATE, Activity.RESULT_OK); } @@ -197,9 +197,9 @@ public final class EIP extends IntentService { private JSONObject eipDefinitionFromPreferences() { JSONObject result = new JSONObject(); try { - String eip_definition_string = preferences.getString(PROVIDER_KEY, ""); - if (!eip_definition_string.isEmpty()) { - result = new JSONObject(eip_definition_string); + String eipDefinitionString = preferences.getString(PROVIDER_KEY, ""); + if (!eipDefinitionString.isEmpty()) { + result = new JSONObject(eipDefinitionString); } } catch (JSONException e) { // TODO Auto-generated catch block @@ -209,20 +209,20 @@ public final class EIP extends IntentService { } private void updateGateways() { - gateways_manager.clearGatewaysAndProfiles(); - gateways_manager.fromEipServiceJson(eip_definition); + gatewaysManager.clearGatewaysAndProfiles(); + gatewaysManager.fromEipServiceJson(eipDefinition); gatewaysToPreferences(); } private void gatewaysFromPreferences() { - String gateways_string = preferences.getString(Gateway.TAG, ""); - gateways_manager = new GatewaysManager(context, preferences); - gateways_manager.addFromString(gateways_string); + String gatewaysString = preferences.getString(Gateway.TAG, ""); + gatewaysManager = new GatewaysManager(context, preferences); + gatewaysManager.addFromString(gatewaysString); preferences.edit().remove(Gateway.TAG).apply(); } private void gatewaysToPreferences() { - String gateways_string = gateways_manager.toString(); + String gateways_string = gatewaysManager.toString(); preferences.edit().putString(Gateway.TAG, gateways_string).commit(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java index b1318def..e9c16dda 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java @@ -32,7 +32,7 @@ public class VpnConfigGenerator { private JSONObject secrets; public final static String TAG = VpnConfigGenerator.class.getSimpleName(); - private final String new_line = System.getProperty("line.separator"); // Platform new line + private final String newLine = System.getProperty("line.separator"); // Platform new line public VpnConfigGenerator(JSONObject general_configuration, JSONObject secrets, JSONObject gateway) { this.general_configuration = general_configuration; @@ -43,25 +43,25 @@ public class VpnConfigGenerator { public String generate() { return generalConfiguration() - + new_line + + newLine + gatewayConfiguration() - + new_line + + newLine + secretsConfiguration() - + new_line + + newLine + androidCustomizations(); } private String generalConfiguration() { - String common_options = ""; + String commonOptions = ""; try { Iterator keys = general_configuration.keys(); while (keys.hasNext()) { String key = keys.next().toString(); - common_options += key + " "; + commonOptions += key + " "; for (String word : String.valueOf(general_configuration.get(key)).split(" ")) - common_options += word + " "; - common_options += new_line; + commonOptions += word + " "; + commonOptions += newLine; } } catch (JSONException e) { @@ -69,31 +69,31 @@ public class VpnConfigGenerator { e.printStackTrace(); } - common_options += "client"; + commonOptions += "client"; - return common_options; + return commonOptions; } private String gatewayConfiguration() { String remotes = ""; - String ip_address_keyword = "ip_address"; - String remote_keyword = "remote"; - String ports_keyword = "ports"; - String protocol_keyword = "protocols"; - String capabilities_keyword = "capabilities"; + String ipAddressKeyword = "ip_address"; + String remoteKeyword = "remote"; + String portsKeyword = "ports"; + String protocolKeyword = "protocols"; + String capabilitiesKeyword = "capabilities"; try { - String ip_address = gateway.getString(ip_address_keyword); - JSONObject capabilities = gateway.getJSONObject(capabilities_keyword); - JSONArray ports = capabilities.getJSONArray(ports_keyword); + String ip_address = gateway.getString(ipAddressKeyword); + JSONObject capabilities = gateway.getJSONObject(capabilitiesKeyword); + JSONArray ports = capabilities.getJSONArray(portsKeyword); for (int i = 0; i < ports.length(); i++) { String port_specific_remotes = ""; int port = ports.getInt(i); - JSONArray protocols = capabilities.getJSONArray(protocol_keyword); + JSONArray protocols = capabilities.getJSONArray(protocolKeyword); for (int j = 0; j < protocols.length(); j++) { String protocol = protocols.optString(j); - String new_remote = remote_keyword + " " + ip_address + " " + port + " " + protocol + new_line; + String new_remote = remoteKeyword + " " + ip_address + " " + port + " " + protocol + newLine; port_specific_remotes += new_remote; } @@ -103,8 +103,8 @@ public class VpnConfigGenerator { // TODO Auto-generated catch block e.printStackTrace(); } - if (remotes.endsWith(new_line)) { - remotes = remotes.substring(0, remotes.lastIndexOf(new_line)); + if (remotes.endsWith(newLine)) { + remotes = remotes.substring(0, remotes.lastIndexOf(newLine)); } return remotes; } @@ -113,26 +113,26 @@ public class VpnConfigGenerator { try { String ca = "" - + new_line + + newLine + secrets.getString(Provider.CA_CERT) - + new_line + + newLine + ""; String key = "" - + new_line + + newLine + secrets.getString(Constants.PROVIDER_PRIVATE_KEY) - + new_line + + newLine + ""; - String openvpn_cert = + String openvpnCert = "" - + new_line + + newLine + secrets.getString(Constants.PROVIDER_VPN_CERTIFICATE) - + new_line + + newLine + ""; - return ca + new_line + key + new_line + openvpn_cert; + return ca + newLine + key + newLine + openvpnCert; } catch (JSONException e) { e.printStackTrace(); return ""; @@ -142,9 +142,9 @@ public class VpnConfigGenerator { private String androidCustomizations() { return "remote-cert-tls server" - + new_line + + newLine + "persist-tun" - + new_line + + newLine + "auth-retry nointeract"; } } diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java index d86da957..5c6355f5 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java @@ -58,11 +58,11 @@ public class SessionDialog extends DialogFragment { } @InjectView(R.id.user_message) - TextView user_message; + TextView userMessage; @InjectView(R.id.username_entered) - EditText username_field; + EditText usernameField; @InjectView(R.id.password_entered) - EditText password_field; + EditText passwordField; public static SessionDialog getInstance(Provider provider, Bundle arguments) { SessionDialog dialog = new SessionDialog(); @@ -118,35 +118,35 @@ public class SessionDialog extends DialogFragment { private void setUp(Bundle arguments) { if (arguments.containsKey(ERRORS.PASSWORD_INVALID_LENGTH.toString())) - password_field.setError(getString(R.string.error_not_valid_password_user_message)); + passwordField.setError(getString(R.string.error_not_valid_password_user_message)); else if (arguments.containsKey(ERRORS.RISEUP_WARNING.toString())) { - user_message.setVisibility(VISIBLE); - user_message.setText(R.string.login_riseup_warning); + userMessage.setVisibility(VISIBLE); + userMessage.setText(R.string.login_riseup_warning); } if (arguments.containsKey(USERNAME)) { String username = arguments.getString(USERNAME); - username_field.setText(username); + usernameField.setText(username); } if (arguments.containsKey(ERRORS.USERNAME_MISSING.toString())) { - username_field.setError(getString(R.string.username_ask)); + usernameField.setError(getString(R.string.username_ask)); } if (arguments.containsKey(getString(R.string.user_message))) { - user_message.setText(arguments.getString(getString(R.string.user_message))); - user_message.setVisibility(VISIBLE); - } else if (user_message.getVisibility() != VISIBLE) - user_message.setVisibility(View.GONE); + userMessage.setText(arguments.getString(getString(R.string.user_message))); + userMessage.setVisibility(VISIBLE); + } else if (userMessage.getVisibility() != VISIBLE) + userMessage.setVisibility(View.GONE); - if (!username_field.getText().toString().isEmpty() && password_field.isFocusable()) - password_field.requestFocus(); + if (!usernameField.getText().toString().isEmpty() && passwordField.isFocusable()) + passwordField.requestFocus(); } private String getEnteredUsername() { - return username_field.getText().toString(); + return usernameField.getText().toString(); } private String getEnteredPassword() { - return password_field.getText().toString(); + return passwordField.getText().toString(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java index 07c102e4..30a34de8 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java @@ -37,7 +37,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia Button button; private UserStatus status; - private boolean allows_registration = false; + private boolean allowsRegistration = false; @Override public void onCreate(Bundle savedInstanceState) { @@ -63,7 +63,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia ButterKnife.inject(this, view); Bundle arguments = getArguments(); - allows_registration = arguments.getBoolean(Provider.ALLOW_REGISTRATION); + allowsRegistration = arguments.getBoolean(Provider.ALLOW_REGISTRATION); handleNewStatus(status); return view; @@ -108,7 +108,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia private void handleNewStatus(UserStatus status) { this.status = status; - if (allows_registration) { + if (allowsRegistration) { if (this.status.inProgress()) showUserSessionProgressBar(); else @@ -134,7 +134,7 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia private void updateButton() { if(status.isLoggedIn() || status.didntLogOut()) button.setText(getActivity().getString(R.string.logout_button)); - else if(allows_registration) { + else if(allowsRegistration) { if (status.isLoggedOut() || status.notLoggedIn()) button.setText(getActivity().getString(R.string.login_button)); else if (status.inProgress()) -- cgit v1.2.3 From 1690dec51d78a27a6a1f7c83d30b28d1ab432f93 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 16:53:54 +0100 Subject: static constant imports --- .../leap/bitmaskclient/AbstractProviderDetailActivity.java | 10 +++++++--- .../java/se/leap/bitmaskclient/BaseConfigurationWizard.java | 12 ++++++++---- app/src/main/java/se/leap/bitmaskclient/MainActivity.java | 4 +++- app/src/main/java/se/leap/bitmaskclient/StartActivity.java | 9 ++++++--- 4 files changed, 24 insertions(+), 11 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java b/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java index c180e43a..a92f8f96 100644 --- a/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/AbstractProviderDetailActivity.java @@ -18,6 +18,10 @@ import java.util.ArrayList; import butterknife.InjectView; +import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; +import static se.leap.bitmaskclient.Constants.PROVIDER_KEY; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; + public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity { final public static String TAG = "providerDetailActivity"; @@ -40,7 +44,7 @@ public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity super.onCreate(savedInstanceState); setContentView(R.layout.provider_detail_fragment); - preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); try { JSONObject providerJson = new JSONObject(preferences.getString(Provider.KEY, "")); domain.setText(providerJson.getString(Provider.DOMAIN)); @@ -92,7 +96,7 @@ public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity private boolean anonAllowed(JSONObject providerJson) { try { JSONObject serviceDescription = providerJson.getJSONObject(Provider.SERVICE); - return serviceDescription.has(Constants.PROVIDER_ALLOW_ANONYMOUS) && serviceDescription.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS); + return serviceDescription.has(PROVIDER_ALLOW_ANONYMOUS) && serviceDescription.getBoolean(PROVIDER_ALLOW_ANONYMOUS); } catch (JSONException e) { return false; } @@ -110,7 +114,7 @@ public abstract class AbstractProviderDetailActivity extends ButterKnifeActivity @Override public void onBackPressed() { SharedPreferences.Editor editor = preferences.edit(); - editor.remove(Provider.KEY).remove(Constants.PROVIDER_ALLOW_ANONYMOUS).remove(Constants.PROVIDER_KEY).apply(); + editor.remove(Provider.KEY).remove(PROVIDER_ALLOW_ANONYMOUS).remove(PROVIDER_KEY).apply(); super.onBackPressed(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 915e948a..1c29a10a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -54,6 +54,10 @@ import se.leap.bitmaskclient.fragments.AboutFragment; import static android.view.View.GONE; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; +import static se.leap.bitmaskclient.Constants.APP_ACTION_QUIT; +import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; +import static se.leap.bitmaskclient.Constants.PROVIDER_KEY; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; import static se.leap.bitmaskclient.ProviderAPI.ERRORS; /** @@ -132,7 +136,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); fragmentManager = new FragmentManagerEnhanced(getSupportFragmentManager()); providerManager = ProviderManager.getInstance(getAssets(), getExternalFilesDir(null)); @@ -210,7 +214,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity e.printStackTrace(); } - if (preferences.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, false)) { + if (preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false)) { mConfigState.putExtra(SERVICES_RETRIEVED, true); downloadVpnCertificate(); @@ -288,7 +292,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity hideProgressBar(); mConfigState.setAction(PROVIDER_NOT_SET); adapter.showAllProviders(); - preferences.edit().remove(Provider.KEY).remove(Constants.PROVIDER_ALLOW_ANONYMOUS).remove(Constants.PROVIDER_KEY).apply(); + preferences.edit().remove(Provider.KEY).remove(PROVIDER_ALLOW_ANONYMOUS).remove(PROVIDER_KEY).apply(); } @Override @@ -307,7 +311,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity private void askDashboardToQuitApp() { Intent askQuit = new Intent(); - askQuit.putExtra(Constants.APP_ACTION_QUIT, Constants.APP_ACTION_QUIT); + askQuit.putExtra(APP_ACTION_QUIT, APP_ACTION_QUIT); setResult(RESULT_CANCELED, askQuit); } diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java index 82a193e7..24145864 100644 --- a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -23,6 +23,8 @@ import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; + public class MainActivity extends AppCompatActivity { @@ -53,7 +55,7 @@ public class MainActivity extends AppCompatActivity { mTitle = getTitle(); fragmentManager = new FragmentManagerEnhanced(getSupportFragmentManager()); - preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, diff --git a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java index 614c6b8d..43d7f152 100644 --- a/app/src/main/java/se/leap/bitmaskclient/StartActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/StartActivity.java @@ -15,6 +15,9 @@ import java.lang.annotation.RetentionPolicy; import de.blinkt.openvpn.core.VpnStatus; import se.leap.bitmaskclient.userstatus.User; +import static se.leap.bitmaskclient.Constants.PREFERENCES_APP_VERSION; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; + /** * Activity shown at startup. Evaluates if App is started for the first time or has been upgraded * and acts and calls another activity accordingly. @@ -39,7 +42,7 @@ public class StartActivity extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); Log.d(TAG, "Started"); @@ -81,7 +84,7 @@ public class StartActivity extends Activity { private int checkAppStart() { try { versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; - previousVersionCode = preferences.getInt(Constants.PREFERENCES_APP_VERSION, -1); + previousVersionCode = preferences.getInt(PREFERENCES_APP_VERSION, -1); // versions do match -> normal start if (versionCode == previousVersionCode) { @@ -135,7 +138,7 @@ public class StartActivity extends Activity { } private void storeAppVersion() { - preferences.edit().putInt(Constants.PREFERENCES_APP_VERSION, versionCode).apply(); + preferences.edit().putInt(PREFERENCES_APP_VERSION, versionCode).apply(); } } -- cgit v1.2.3 From 8909b3e9ea63c8dc78abf89de69b44d3d172f763 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 16:54:29 +0100 Subject: fix handle version in dashboard --- app/src/main/java/se/leap/bitmaskclient/Dashboard.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 3e8668de..3ed9de0c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -98,7 +98,7 @@ public class Dashboard extends ButterKnifeActivity { providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), dashboardReceiver); - if (handledVersion) { + if (!handledVersion) { handleVersion(); handledVersion = true; } -- cgit v1.2.3 From 153e35707ed2854d89c61fdb9f82a6e9ec0db9cc Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 17:03:14 +0100 Subject: more static constant import and import cleanup --- .../main/java/se/leap/bitmaskclient/Dashboard.java | 42 +++++++++++++--------- .../java/se/leap/bitmaskclient/OnBootReceiver.java | 6 ++-- .../java/se/leap/bitmaskclient/ProviderAPI.java | 4 +-- .../leap/bitmaskclient/ProviderApiManagerBase.java | 12 ++++--- .../java/se/leap/bitmaskclient/VpnFragment.java | 3 +- .../drawer/NavigationDrawerFragment.java | 18 +++++----- .../se/leap/bitmaskclient/eip/GatewaysManager.java | 8 +++-- .../leap/bitmaskclient/eip/VpnConfigGenerator.java | 8 +++-- 8 files changed, 61 insertions(+), 40 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 3ed9de0c..07c6fdfb 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -47,10 +47,18 @@ import se.leap.bitmaskclient.userstatus.SessionDialog; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; +import static se.leap.bitmaskclient.Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE; +import static se.leap.bitmaskclient.Constants.APP_ACTION_QUIT; import static se.leap.bitmaskclient.Constants.EIP_IS_ALWAYS_ON; import static se.leap.bitmaskclient.Constants.EIP_RESTART_ON_BOOT; +import static se.leap.bitmaskclient.Constants.PREFERENCES_APP_VERSION; +import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; +import static se.leap.bitmaskclient.Constants.PROVIDER_CONFIGURED; +import static se.leap.bitmaskclient.Constants.PROVIDER_KEY; import static se.leap.bitmaskclient.Constants.REQUEST_CODE_CONFIGURE_LEAP; +import static se.leap.bitmaskclient.Constants.REQUEST_CODE_KEY; import static se.leap.bitmaskclient.Constants.REQUEST_CODE_SWITCH_PROVIDER; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; /** * The main user facing Activity of Bitmask Android, consisting of status, controls, @@ -93,7 +101,7 @@ public class Dashboard extends ButterKnifeActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dashboardReceiver = new DashboardReceiver(this); - preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); fragment_manager = new FragmentManagerEnhanced(getSupportFragmentManager()); providerAPI_result_receiver = new ProviderAPIResultReceiver(new Handler(), dashboardReceiver); @@ -136,7 +144,7 @@ public class Dashboard extends ButterKnifeActivity { private boolean providerInSharedPreferences() { return preferences != null && - preferences.getBoolean(Constants.PROVIDER_CONFIGURED, false); + preferences.getBoolean(PROVIDER_CONFIGURED, false); } @@ -166,7 +174,7 @@ public class Dashboard extends ButterKnifeActivity { switch (versionCode) { case 91: // 0.6.0 without Bug #5999 case 101: // 0.8.0 - if (!preferences.getString(Constants.PROVIDER_KEY, "").isEmpty()) + if (!preferences.getString(PROVIDER_KEY, "").isEmpty()) eip_fragment.updateEipService(); break; } @@ -188,7 +196,7 @@ public class Dashboard extends ButterKnifeActivity { } else if (intent.hasExtra(EIP_RESTART_ON_BOOT)) { Log.d(TAG, "Dashboard: EIP_RESTART_ON_BOOT"); prepareEIP(null); - } else if (intent.hasExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { + } else if (intent.hasExtra(APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { Log.d(TAG, "Dashboard: Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE"); handleConfigureAlwaysOn(getIntent()); } @@ -207,7 +215,7 @@ public class Dashboard extends ButterKnifeActivity { sessionDialog(Bundle.EMPTY); } - } else if (resultCode == RESULT_CANCELED && data != null && data.hasExtra(Constants.APP_ACTION_QUIT)) { + } else if (resultCode == RESULT_CANCELED && data != null && data.hasExtra(APP_ACTION_QUIT)) { finish(); } else configErrorDialog(); @@ -222,9 +230,9 @@ public class Dashboard extends ButterKnifeActivity { } private void handleConfigureAlwaysOn(Intent intent) { - intent.removeExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE); + intent.removeExtra(APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE); Log.d(TAG, "start Configuration wizard!"); - startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_CONFIGURE_LEAP); + startActivityForResult(new Intent(this, ConfigurationWizard.class), REQUEST_CODE_CONFIGURE_LEAP); } private void prepareEIP(Bundle savedInstanceState) { @@ -244,14 +252,14 @@ public class Dashboard extends ButterKnifeActivity { } private void configureLeapProvider() { - if (getIntent().hasExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { - getIntent().removeExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE); + if (getIntent().hasExtra(APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE)) { + getIntent().removeExtra(APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE); } - startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_CONFIGURE_LEAP); + startActivityForResult(new Intent(this, ConfigurationWizard.class), REQUEST_CODE_CONFIGURE_LEAP); } @SuppressLint("CommitPrefEdits") private void providerToPreferences(Provider provider) { - preferences.edit().putBoolean(Constants.PROVIDER_CONFIGURED, true). + preferences.edit().putBoolean(PROVIDER_CONFIGURED, true). putString(Provider.MAIN_URL, provider.getMainUrl().toString()). putString(Provider.KEY, provider.getDefinition().toString()).apply(); } @@ -265,13 +273,13 @@ public class Dashboard extends ButterKnifeActivity { .setPositiveButton(getResources().getString(R.string.setup_error_configure_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - startActivityForResult(new Intent(getApplicationContext(), ConfigurationWizard.class), Constants.REQUEST_CODE_CONFIGURE_LEAP); + startActivityForResult(new Intent(getApplicationContext(), ConfigurationWizard.class), REQUEST_CODE_CONFIGURE_LEAP); } }) .setNegativeButton(getResources().getString(R.string.setup_error_close_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - preferences.edit().remove(Provider.KEY).remove(Constants.PROVIDER_CONFIGURED).apply(); + preferences.edit().remove(Provider.KEY).remove(PROVIDER_CONFIGURED).apply(); finish(); } }) @@ -385,7 +393,7 @@ public class Dashboard extends ButterKnifeActivity { // TODO MOVE TO VPNManager(?) public static void downloadVpnCertificate() { boolean is_authenticated = User.loggedIn(); - boolean allowed_anon = preferences.getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, false); + boolean allowed_anon = preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false); if (allowed_anon || is_authenticated) ProviderAPICommand.execute(Bundle.EMPTY, ProviderAPI.DOWNLOAD_CERTIFICATE, providerAPI_result_receiver); else @@ -419,7 +427,7 @@ public class Dashboard extends ButterKnifeActivity { if (entry.getKey().startsWith(Provider.KEY + ".") || entry.getKey().startsWith(Provider.CA_CERT + ".") || entry.getKey().startsWith(Provider.CA_CERT_FINGERPRINT + "." )|| - entry.getKey().equals(Constants.PREFERENCES_APP_VERSION) + entry.getKey().equals(PREFERENCES_APP_VERSION) ) { continue; } @@ -433,7 +441,7 @@ public class Dashboard extends ButterKnifeActivity { preferenceEditor.apply(); switching_provider = false; - startActivityForResult(new Intent(this, ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); + startActivityForResult(new Intent(this, ConfigurationWizard.class), REQUEST_CODE_SWITCH_PROVIDER); } public static class DashboardReceiver implements ProviderAPIResultReceiver.Receiver{ @@ -478,7 +486,7 @@ public class Dashboard extends ButterKnifeActivity { @Override public void startActivityForResult(Intent intent, int requestCode) { - intent.putExtra(Constants.REQUEST_CODE_KEY, requestCode); + intent.putExtra(REQUEST_CODE_KEY, requestCode); super.startActivityForResult(intent, requestCode); } diff --git a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java index aa661723..2a8aa42f 100644 --- a/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java +++ b/app/src/main/java/se/leap/bitmaskclient/OnBootReceiver.java @@ -7,9 +7,11 @@ import android.content.SharedPreferences; import android.util.Log; import static android.content.Intent.ACTION_BOOT_COMPLETED; +import static se.leap.bitmaskclient.Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE; import static se.leap.bitmaskclient.Constants.EIP_IS_ALWAYS_ON; import static se.leap.bitmaskclient.Constants.EIP_RESTART_ON_BOOT; import static se.leap.bitmaskclient.Constants.PROVIDER_VPN_CERTIFICATE; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; public class OnBootReceiver extends BroadcastReceiver { @@ -22,7 +24,7 @@ public class OnBootReceiver extends BroadcastReceiver { if (intent == null || !ACTION_BOOT_COMPLETED.equals(intent.getAction())) { return; } - preferences = context.getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); + preferences = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE); boolean providerConfigured = !preferences.getString(PROVIDER_VPN_CERTIFICATE, "").isEmpty(); boolean startOnBoot = preferences.getBoolean(EIP_RESTART_ON_BOOT, false); boolean isAlwaysOnConfigured = preferences.getBoolean(EIP_IS_ALWAYS_ON, false); @@ -41,7 +43,7 @@ public class OnBootReceiver extends BroadcastReceiver { } else { if (isAlwaysOnConfigured) { Intent dashboardIntent = new Intent(context, Dashboard.class); - dashboardIntent.putExtra(Constants.APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE, true); + dashboardIntent.putExtra(APP_ACTION_CONFIGURE_ALWAYS_ON_PROFILE, true); dashboardIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(dashboardIntent); } diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java b/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java index 5a6aabc0..3dc93539 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java @@ -21,7 +21,7 @@ import android.app.IntentService; import android.content.Intent; import android.content.SharedPreferences; -import de.blinkt.openvpn.core.Preferences; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; /** * Implements HTTP api methods (encapsulated in {{@link ProviderApiManager}}) @@ -117,7 +117,7 @@ public class ProviderAPI extends IntentService implements ProviderApiManagerBase private ProviderApiManager initApiManager() { - SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE); + SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); OkHttpClientGenerator clientGenerator = new OkHttpClientGenerator(preferences, getResources()); return new ProviderApiManager(preferences, getResources(), clientGenerator, this); } diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java index 9f5fdc2d..f7bc0925 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java @@ -54,6 +54,10 @@ import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatus; import static se.leap.bitmaskclient.ConfigHelper.getFingerprintFromCertificate; +import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOWED_REGISTERED; +import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; +import static se.leap.bitmaskclient.Constants.PROVIDER_PRIVATE_KEY; +import static se.leap.bitmaskclient.Constants.PROVIDER_VPN_CERTIFICATE; import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CERTIFICATE_PINNING; import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_CORRUPTED_PROVIDER_JSON; import static se.leap.bitmaskclient.DownloadFailedDialog.DOWNLOAD_ERRORS.ERROR_INVALID_CERTIFICATE; @@ -674,8 +678,8 @@ public abstract class ProviderApiManagerBase { //valid certificate: skip download, save loaded provider CA cert and provider definition directly try { preferences.edit().putString(Provider.KEY, providerDefinition.toString()). - putBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOW_ANONYMOUS)). - putBoolean(Constants.PROVIDER_ALLOWED_REGISTERED, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(Constants.PROVIDER_ALLOWED_REGISTERED)). + putBoolean(PROVIDER_ALLOW_ANONYMOUS, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(PROVIDER_ALLOW_ANONYMOUS)). + putBoolean(PROVIDER_ALLOWED_REGISTERED, providerDefinition.getJSONObject(Provider.SERVICE).getBoolean(PROVIDER_ALLOWED_REGISTERED)). putString(Provider.CA_CERT, providerCaCert).commit(); CA_CERT_DOWNLOADED = true; PROVIDER_JSON_DOWNLOADED = true; @@ -912,11 +916,11 @@ public abstract class ProviderApiManagerBase { RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); + preferences.edit().putString(PROVIDER_PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----").commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); - preferences.edit().putString(Constants.PROVIDER_VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); + preferences.edit().putString(PROVIDER_VPN_CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----").commit(); return true; } catch (CertificateException e) { // TODO Auto-generated catch block diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index 0af23917..8ea891cc 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -64,6 +64,7 @@ import static se.leap.bitmaskclient.Constants.EIP_RESTART_ON_BOOT; import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOWED_REGISTERED; import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; import static se.leap.bitmaskclient.Constants.PROVIDER_VPN_CERTIFICATE; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; public class VpnFragment extends Fragment implements Observer { @@ -114,7 +115,7 @@ public class VpnFragment extends Fragment implements Observer { eipStatus = EipStatus.getInstance(); eipStatus.addObserver(this); eipReceiver = new EIPReceiver(new Handler()); - preferences = getActivity().getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); + preferences = getActivity().getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE); } @Override diff --git a/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java index e7217ad1..566134dd 100644 --- a/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/drawer/NavigationDrawerFragment.java @@ -3,16 +3,16 @@ package se.leap.bitmaskclient.drawer; import android.content.Context; import android.content.Intent; -import android.support.v4.app.FragmentManager; -import android.support.v7.app.ActionBarDrawerToggle; -import android.support.v4.app.Fragment; -import android.support.v4.view.GravityCompat; -import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; +import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; @@ -28,7 +28,6 @@ import android.widget.ListView; import android.widget.Toast; import se.leap.bitmaskclient.ConfigurationWizard; -import se.leap.bitmaskclient.Constants; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.VpnFragment; @@ -37,6 +36,9 @@ import se.leap.bitmaskclient.fragments.LogFragment; import se.leap.bitmaskclient.userstatus.User; import se.leap.bitmaskclient.userstatus.UserStatusFragment; +import static se.leap.bitmaskclient.Constants.REQUEST_CODE_SWITCH_PROVIDER; +import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; + /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the @@ -86,7 +88,7 @@ public class NavigationDrawerFragment extends Fragment { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); - preferences = getActivity().getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); + preferences = getActivity().getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); @@ -317,7 +319,7 @@ public class NavigationDrawerFragment extends Fragment { // TODO STOP VPN // if (provider.hasEIP()) eip_fragment.stopEipIfPossible(); preferences.edit().clear().apply(); - startActivityForResult(new Intent(getActivity(), ConfigurationWizard.class), Constants.REQUEST_CODE_SWITCH_PROVIDER); + startActivityForResult(new Intent(getActivity(), ConfigurationWizard.class), REQUEST_CODE_SWITCH_PROVIDER); break; case 2: mTitle = getString(R.string.log_fragment_title); diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java index 43c16d00..0b330ed9 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java @@ -36,9 +36,11 @@ import java.util.List; import de.blinkt.openvpn.VpnProfile; import de.blinkt.openvpn.core.Connection; import de.blinkt.openvpn.core.ProfileManager; -import se.leap.bitmaskclient.Constants; import se.leap.bitmaskclient.Provider; +import static se.leap.bitmaskclient.Constants.PROVIDER_PRIVATE_KEY; +import static se.leap.bitmaskclient.Constants.PROVIDER_VPN_CERTIFICATE; + /** * @author parmegv */ @@ -124,8 +126,8 @@ public class GatewaysManager { JSONObject result = new JSONObject(); try { result.put(Provider.CA_CERT, preferences.getString(Provider.CA_CERT, "")); - result.put(Constants.PROVIDER_PRIVATE_KEY, preferences.getString(Constants.PROVIDER_PRIVATE_KEY, "")); - result.put(Constants.PROVIDER_VPN_CERTIFICATE, preferences.getString(Constants.PROVIDER_VPN_CERTIFICATE, "")); + result.put(PROVIDER_PRIVATE_KEY, preferences.getString(PROVIDER_PRIVATE_KEY, "")); + result.put(PROVIDER_VPN_CERTIFICATE, preferences.getString(PROVIDER_VPN_CERTIFICATE, "")); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java index e9c16dda..6f0ccf18 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VpnConfigGenerator.java @@ -22,9 +22,11 @@ import org.json.JSONObject; import java.util.Iterator; -import se.leap.bitmaskclient.Constants; import se.leap.bitmaskclient.Provider; +import static se.leap.bitmaskclient.Constants.PROVIDER_PRIVATE_KEY; +import static se.leap.bitmaskclient.Constants.PROVIDER_VPN_CERTIFICATE; + public class VpnConfigGenerator { private JSONObject general_configuration; @@ -121,14 +123,14 @@ public class VpnConfigGenerator { String key = "" + newLine - + secrets.getString(Constants.PROVIDER_PRIVATE_KEY) + + secrets.getString(PROVIDER_PRIVATE_KEY) + newLine + ""; String openvpnCert = "" + newLine - + secrets.getString(Constants.PROVIDER_VPN_CERTIFICATE) + + secrets.getString(PROVIDER_VPN_CERTIFICATE) + newLine + ""; -- cgit v1.2.3 From 583e51a4150123faaf5445c680ca5aaff5f5aad7 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 17:19:44 +0100 Subject: discussions on dashboard --- app/src/main/java/se/leap/bitmaskclient/Dashboard.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 07c6fdfb..901dee89 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -18,6 +18,7 @@ package se.leap.bitmaskclient; import android.annotation.SuppressLint; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; @@ -320,7 +321,7 @@ public class Dashboard extends ButterKnifeActivity { * has caused to start Dashboard * @return the created VPNFragment */ - public static VpnFragment prepareEipFragment(boolean hideAndTurnOnEipOnBoot) { + public VpnFragment prepareEipFragment(boolean hideAndTurnOnEipOnBoot) { VpnFragment eip_fragment = new VpnFragment(); if (hideAndTurnOnEipOnBoot && !isAlwaysOn()) { @@ -338,7 +339,7 @@ public class Dashboard extends ButterKnifeActivity { * checks if Android's VPN feature 'always-on' is enabled for Bitmask * @return true if 'always-on' is enabled false if not */ - private static boolean isAlwaysOn() { + private boolean isAlwaysOn() { return preferences.getBoolean(EIP_IS_ALWAYS_ON, false); } @@ -444,7 +445,7 @@ public class Dashboard extends ButterKnifeActivity { startActivityForResult(new Intent(this, ConfigurationWizard.class), REQUEST_CODE_SWITCH_PROVIDER); } - public static class DashboardReceiver implements ProviderAPIResultReceiver.Receiver{ + private static class DashboardReceiver implements ProviderAPIResultReceiver.Receiver{ private Dashboard dashboard; -- cgit v1.2.3 From bfc1f97475f7d29e2c8a51ef80b0020ed92ce092 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 17:20:39 +0100 Subject: rename context from activity to context --- .../main/java/se/leap/bitmaskclient/fragments/LogFragment.java | 4 ++-- .../main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java | 8 ++++---- .../java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java b/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java index 3917683d..3d85b4ad 100644 --- a/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/fragments/LogFragment.java @@ -635,8 +635,8 @@ public class LogFragment extends ListFragment implements StateListener, SeekBar. } @Override - public void onAttach(Context activity) { - super.onAttach(activity); + public void onAttach(Context context) { + super.onAttach(context); if (getResources().getBoolean(R.bool.logSildersAlwaysVisible)) { mShowOptionsLayout = true; if (mOptionsLayout != null) diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java index 5c6355f5..29d4f01d 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/SessionDialog.java @@ -165,13 +165,13 @@ public class SessionDialog extends DialogFragment { SessionDialogInterface interface_with_Dashboard; @Override - public void onAttach(Context activity) { - super.onAttach(activity); + public void onAttach(Context context) { + super.onAttach(context); try { - interface_with_Dashboard = (SessionDialogInterface) ((AppCompatActivity) activity).getSupportFragmentManager().getFragments().get(0); + interface_with_Dashboard = (SessionDialogInterface) ((AppCompatActivity) context).getSupportFragmentManager().getFragments().get(0); } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() + throw new ClassCastException(context.toString() + " must implement LogInDialogListener"); } } diff --git a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java index 30a34de8..0f1d0cdb 100644 --- a/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/userstatus/UserStatusFragment.java @@ -70,8 +70,8 @@ public class UserStatusFragment extends Fragment implements Observer, SessionDia } @Override - public void onAttach(Context activity) { - super.onAttach(activity); + public void onAttach(Context context) { + super.onAttach(context); } public void restoreSessionStatus(Bundle savedInstanceState) { -- cgit v1.2.3 From 1e6e2190befc6c83874152a97a550c765c121e14 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 17:29:42 +0100 Subject: clean up MainActivity --- .../java/se/leap/bitmaskclient/MainActivity.java | 59 ++-------------------- 1 file changed, 3 insertions(+), 56 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java index 24145864..41e496bb 100644 --- a/app/src/main/java/se/leap/bitmaskclient/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/MainActivity.java @@ -1,47 +1,25 @@ package se.leap.bitmaskclient; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; -import android.support.v7.app.ActionBar; +import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.support.v4.widget.DrawerLayout; import se.leap.bitmaskclient.drawer.NavigationDrawerFragment; -import se.leap.bitmaskclient.fragments.LogFragment; import se.leap.bitmaskclient.userstatus.SessionDialog; -import se.leap.bitmaskclient.userstatus.User; -import se.leap.bitmaskclient.userstatus.UserStatusFragment; - -import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; public class MainActivity extends AppCompatActivity { private static Provider provider = new Provider(); private static FragmentManagerEnhanced fragmentManager; - private SharedPreferences preferences; /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ - private NavigationDrawerFragment mNavigationDrawerFragment; - - /** - * Used to store the last screen title. For use in {@link #restoreActionBar()}. - */ - private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { @@ -50,48 +28,17 @@ public class MainActivity extends AppCompatActivity { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); - mNavigationDrawerFragment = (NavigationDrawerFragment) + NavigationDrawerFragment navigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); - mTitle = getTitle(); fragmentManager = new FragmentManagerEnhanced(getSupportFragmentManager()); - preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); // Set up the drawer. - mNavigationDrawerFragment.setUp( + navigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } - /** - * A placeholder fragment containing a simple view. - */ - public static class PlaceholderFragment extends Fragment { - public PlaceholderFragment() { - } - - /** - * Returns a new instance of this fragment for the given section - * number. - */ - public static PlaceholderFragment newInstance() { - PlaceholderFragment fragment = new PlaceholderFragment(); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_main, container, false); - return rootView; - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - } - } - public static void sessionDialog(Bundle resultData) { try { FragmentTransaction transaction = fragmentManager.removePreviousFragment(SessionDialog.TAG); -- cgit v1.2.3 From 1ca4a7c9c4f10f60adb2554e87d51fff99f8a2b2 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 17:34:18 +0100 Subject: use variable instead of function --- app/src/main/java/se/leap/bitmaskclient/VpnFragment.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java index 8ea891cc..6dab1b27 100644 --- a/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/VpnFragment.java @@ -306,7 +306,7 @@ public class VpnFragment extends Fragment implements Observer { eipStatus = (EipStatus) observable; Activity activity = getActivity(); if (activity != null) { - getActivity().runOnUiThread(new Runnable() { + activity.runOnUiThread(new Runnable() { @Override public void run() { handleNewState(); -- cgit v1.2.3 From cbb8250b4e8464a0d66e17a5c695d0e44fc26c6c Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sat, 13 Jan 2018 23:37:31 +0100 Subject: allow rotation of ConfigWizard --- .../bitmaskclient/BaseConfigurationWizard.java | 57 ++++++++++++++++------ .../leap/bitmaskclient/ProviderApiManagerBase.java | 1 - 2 files changed, 41 insertions(+), 17 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 1c29a10a..35cc23fd 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -59,6 +59,8 @@ import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; import static se.leap.bitmaskclient.Constants.PROVIDER_KEY; import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; import static se.leap.bitmaskclient.ProviderAPI.ERRORS; +import static se.leap.bitmaskclient.ProviderAPI.SET_UP_PROVIDER; +import static se.leap.bitmaskclient.ProviderAPI.UPDATE_PROGRESSBAR; /** * abstract base Activity that builds and shows the list of known available providers. @@ -91,7 +93,8 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity final protected static String PROVIDER_NOT_SET = "PROVIDER NOT SET"; final protected static String SETTING_UP_PROVIDER = "PROVIDER GETS SET"; - final private static String PENDING_SHOW_PROVIDER_DETAILS = "PROVIDER DETAILS SHOWN"; + final private static String PENDING_SHOW_PROVIDER_DETAILS = "PENDING PROVIDER DETAILS"; + final private static String SHOWING_PROVIDER_DETAILS = "SHOWING PROVIDER DETAILS SHOWN"; final private static String PENDING_SHOW_FAILED_DIALOG = "SHOW FAILED DIALOG"; final private static String REASON_TO_FAIL = "REASON TO FAIL"; final protected static String PROVIDER_SET = "PROVIDER SET"; @@ -99,16 +102,17 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity final private static String PROGRESSBAR_TEXT = TAG + "PROGRESSBAR_TEXT"; final private static String PROGRESSBAR_NUMBER = TAG + "PROGRESSBAR_NUMBER"; + final private static String ACTIVITY_STATE = "ACTIVITY STATE"; public ProviderAPIResultReceiver providerAPIResultReceiver; - private BaseConfigurationWizard.providerAPIBroadcastReceiverUpdate providerAPIBroadcastReceiverUpdate; + private ProviderAPIBroadcastReceiver providerAPIBroadcastReceiver; protected static SharedPreferences preferences; FragmentManagerEnhanced fragmentManager; //TODO: add some states (values for progressbarText) about ongoing setup or remove that field private String progressbarText = ""; - + private boolean isActivityShowing; public abstract void retrySetUpProvider(); @@ -129,6 +133,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity outState.putInt(PROGRESSBAR_NUMBER, mProgressBar.getProgress()); if (progressbarDescription != null) outState.putString(PROGRESSBAR_TEXT, progressbarDescription.getText().toString()); + outState.putString(ACTIVITY_STATE, mConfigState.getAction()); outState.putParcelable(Provider.KEY, selectedProvider); super.onSaveInstanceState(outState); } @@ -152,23 +157,30 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity private void restoreState(Bundle savedInstanceState) { progressbarText = savedInstanceState.getString(PROGRESSBAR_TEXT, ""); selectedProvider = savedInstanceState.getParcelable(Provider.KEY); + mConfigState.setAction(savedInstanceState.getString(ACTIVITY_STATE, PROVIDER_NOT_SET)); } @Override protected void onResume() { super.onResume(); + hideProgressBar(); + isActivityShowing = true; if (SETTING_UP_PROVIDER.equals(mConfigState.getAction())) { - cancelAndShowAllProviders(); + showProgressBar(); + adapter.hideAllBut(adapter.indexOf(selectedProvider)); + // TODO find a better replacement! This can lead to loops + onItemSelectedLogic(); } else if (PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction())) { showProviderDetails(); } else if (PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction())) { showDownloadFailedDialog(mConfigState.getStringExtra(REASON_TO_FAIL)); + } else if (SHOWING_PROVIDER_DETAILS.equals(mConfigState.getAction())) { + cancelAndShowAllProviders(); } } private void setUpInitialUI() { setContentView(R.layout.configuration_wizard_activity); - hideProgressBar(); } @@ -185,20 +197,27 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity progressbarDescription.setVisibility(VISIBLE); } + @Override + protected void onPause() { + super.onPause(); + isActivityShowing = false; + } + @Override protected void onDestroy() { super.onDestroy(); - if (providerAPIBroadcastReceiverUpdate != null) - unregisterReceiver(providerAPIBroadcastReceiverUpdate); + if (providerAPIBroadcastReceiver != null) + unregisterReceiver(providerAPIBroadcastReceiver); } private void setUpProviderAPIResultReceiver() { providerAPIResultReceiver = new ProviderAPIResultReceiver(new Handler(), this); - providerAPIBroadcastReceiverUpdate = new providerAPIBroadcastReceiverUpdate(); + providerAPIBroadcastReceiver = new ProviderAPIBroadcastReceiver(); - IntentFilter update_intent_filter = new IntentFilter(ProviderAPI.UPDATE_PROGRESSBAR); - update_intent_filter.addCategory(Intent.CATEGORY_DEFAULT); - registerReceiver(providerAPIBroadcastReceiverUpdate, update_intent_filter); + IntentFilter updateIntentFilter = new IntentFilter(UPDATE_PROGRESSBAR); + updateIntentFilter.addAction(SET_UP_PROVIDER); + updateIntentFilter.addCategory(Intent.CATEGORY_DEFAULT); + registerReceiver(providerAPIBroadcastReceiver, updateIntentFilter); } @Override @@ -222,7 +241,6 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity mProgressBar.incrementProgressBy(1); hideProgressBar(); - showProviderDetails(); } } else if (resultCode == ProviderAPI.PROVIDER_NOK) { mConfigState.setAction(PROVIDER_NOT_SET); @@ -409,9 +427,16 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity * */ public void showProviderDetails() { - Intent intent = new Intent(this, ProviderDetailActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); - startActivity(intent); + // show only if current activity is shown + if (isActivityShowing) { + mConfigState.setAction(SHOWING_PROVIDER_DETAILS); + Intent intent = new Intent(this, ProviderDetailActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + startActivity(intent); + } else { + // may be called AFTER onSaveInstanceState (!) + mConfigState.setAction(PENDING_SHOW_PROVIDER_DETAILS); + } } @Override @@ -440,7 +465,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity adapter.showAllProviders(); } - public class providerAPIBroadcastReceiverUpdate extends BroadcastReceiver { + public class ProviderAPIBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int update = intent.getIntExtra(ProviderAPI.CURRENT_PROGRESS, 0); diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java index f7bc0925..9b288122 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java @@ -433,7 +433,6 @@ public abstract class ProviderApiManagerBase { intentUpdate.addCategory(Intent.CATEGORY_DEFAULT); intentUpdate.putExtra(CURRENT_PROGRESS, progress); serviceCallback.broadcastProgress(intentUpdate); - //sendBroadcast(intentUpdate); } /** -- cgit v1.2.3 From deb8f0c1192a36c9aa66ab16bfd5e26357096821 Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Sun, 14 Jan 2018 00:03:09 +0100 Subject: update insecure configuration wizard as well --- .../main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 35cc23fd..f30c962c 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -158,6 +158,13 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity progressbarText = savedInstanceState.getString(PROGRESSBAR_TEXT, ""); selectedProvider = savedInstanceState.getParcelable(Provider.KEY); mConfigState.setAction(savedInstanceState.getString(ACTIVITY_STATE, PROVIDER_NOT_SET)); + + if (SETTING_UP_PROVIDER.equals(mConfigState.getAction()) || + PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction()) || + PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction()) + ) { + onItemSelectedUi(); + } } @Override -- cgit v1.2.3 From 4f536f457da8bb7ab0316f6de7703437ad0ce58f Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 16 Jan 2018 17:41:47 +0100 Subject: resolve commented issues * recreate activity correctly after changing orientation * replace getApplicationActivity --- .../bitmaskclient/BaseConfigurationWizard.java | 154 +++++++++++++-------- .../main/java/se/leap/bitmaskclient/Dashboard.java | 2 +- .../java/se/leap/bitmaskclient/LoginActivity.java | 6 + .../java/se/leap/bitmaskclient/ProviderAPI.java | 7 +- .../leap/bitmaskclient/ProviderApiManagerBase.java | 60 +++++--- 5 files changed, 151 insertions(+), 78 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index f30c962c..64ea4779 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -26,6 +26,7 @@ import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentTransaction; +import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; @@ -58,8 +59,15 @@ import static se.leap.bitmaskclient.Constants.APP_ACTION_QUIT; import static se.leap.bitmaskclient.Constants.PROVIDER_ALLOW_ANONYMOUS; import static se.leap.bitmaskclient.Constants.PROVIDER_KEY; import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; +import static se.leap.bitmaskclient.ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE; import static se.leap.bitmaskclient.ProviderAPI.ERRORS; -import static se.leap.bitmaskclient.ProviderAPI.SET_UP_PROVIDER; +import static se.leap.bitmaskclient.ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_API_EVENT; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_NOK; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_OK; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_SET_UP; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_CODE; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_KEY; import static se.leap.bitmaskclient.ProviderAPI.UPDATE_PROGRESSBAR; /** @@ -93,11 +101,9 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity final protected static String PROVIDER_NOT_SET = "PROVIDER NOT SET"; final protected static String SETTING_UP_PROVIDER = "PROVIDER GETS SET"; - final private static String PENDING_SHOW_PROVIDER_DETAILS = "PENDING PROVIDER DETAILS"; - final private static String SHOWING_PROVIDER_DETAILS = "SHOWING PROVIDER DETAILS SHOWN"; + final private static String SHOWING_PROVIDER_DETAILS = "SHOWING PROVIDER DETAILS"; final private static String PENDING_SHOW_FAILED_DIALOG = "SHOW FAILED DIALOG"; final private static String REASON_TO_FAIL = "REASON TO FAIL"; - final protected static String PROVIDER_SET = "PROVIDER SET"; final protected static String SERVICES_RETRIEVED = "SERVICES RETRIEVED"; final private static String PROGRESSBAR_TEXT = TAG + "PROGRESSBAR_TEXT"; @@ -110,7 +116,6 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity protected static SharedPreferences preferences; FragmentManagerEnhanced fragmentManager; //TODO: add some states (values for progressbarText) about ongoing setup or remove that field - private String progressbarText = ""; private boolean isActivityShowing; @@ -155,12 +160,10 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity } private void restoreState(Bundle savedInstanceState) { - progressbarText = savedInstanceState.getString(PROGRESSBAR_TEXT, ""); selectedProvider = savedInstanceState.getParcelable(Provider.KEY); mConfigState.setAction(savedInstanceState.getString(ACTIVITY_STATE, PROVIDER_NOT_SET)); if (SETTING_UP_PROVIDER.equals(mConfigState.getAction()) || - PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction()) || PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction()) ) { onItemSelectedUi(); @@ -169,16 +172,15 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity @Override protected void onResume() { + Log.d(TAG, "resuming with ConfigState: " + mConfigState.getAction()); super.onResume(); hideProgressBar(); isActivityShowing = true; if (SETTING_UP_PROVIDER.equals(mConfigState.getAction())) { showProgressBar(); adapter.hideAllBut(adapter.indexOf(selectedProvider)); - // TODO find a better replacement! This can lead to loops - onItemSelectedLogic(); - } else if (PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction())) { - showProviderDetails(); + checkProviderSetUp(); + showDownloadFailedDialog(null); } else if (PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction())) { showDownloadFailedDialog(mConfigState.getStringExtra(REASON_TO_FAIL)); } else if (SHOWING_PROVIDER_DETAILS.equals(mConfigState.getAction())) { @@ -215,6 +217,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity super.onDestroy(); if (providerAPIBroadcastReceiver != null) unregisterReceiver(providerAPIBroadcastReceiver); + providerAPIResultReceiver = null; } private void setUpProviderAPIResultReceiver() { @@ -222,49 +225,60 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity providerAPIBroadcastReceiver = new ProviderAPIBroadcastReceiver(); IntentFilter updateIntentFilter = new IntentFilter(UPDATE_PROGRESSBAR); - updateIntentFilter.addAction(SET_UP_PROVIDER); + updateIntentFilter.addAction(PROVIDER_API_EVENT); updateIntentFilter.addCategory(Intent.CATEGORY_DEFAULT); registerReceiver(providerAPIBroadcastReceiver, updateIntentFilter); } - @Override - public void onReceiveResult(int resultCode, Bundle resultData) { - if (resultCode == ProviderAPI.PROVIDER_OK) { - try { - String providerJsonString = preferences.getString(Provider.KEY, ""); - if (!providerJsonString.isEmpty()) - selectedProvider.define(new JSONObject(providerJsonString)); - String caCert = preferences.getString(Provider.CA_CERT, ""); - selectedProvider.setCACert(caCert); - } catch (JSONException e) { - e.printStackTrace(); - } - - if (preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false)) { - mConfigState.putExtra(SERVICES_RETRIEVED, true); - - downloadVpnCertificate(); - } else { - mProgressBar.incrementProgressBy(1); - hideProgressBar(); - - } - } else if (resultCode == ProviderAPI.PROVIDER_NOK) { - mConfigState.setAction(PROVIDER_NOT_SET); - preferences.edit().remove(Provider.KEY).apply(); + void handleProviderSetUp() { + try { + String providerJsonString = preferences.getString(Provider.KEY, ""); + if (!providerJsonString.isEmpty()) + selectedProvider.define(new JSONObject(providerJsonString)); + String caCert = preferences.getString(Provider.CA_CERT, ""); + selectedProvider.setCACert(caCert); + } catch (JSONException e) { + e.printStackTrace(); + } - setResult(RESULT_CANCELED, mConfigState); + if (preferences.getBoolean(PROVIDER_ALLOW_ANONYMOUS, false)) { + mConfigState.putExtra(SERVICES_RETRIEVED, true); - String reason_to_fail = resultData.getString(ERRORS); - showDownloadFailedDialog(reason_to_fail); - } else if (resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE) { + downloadVpnCertificate(); + } else { mProgressBar.incrementProgressBy(1); hideProgressBar(); + showProviderDetails(); - } else if (resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE) { - mConfigState.setAction(PROVIDER_NOT_SET); - hideProgressBar(); - setResult(RESULT_CANCELED, mConfigState); + } + } + + void handleProviderSetupFailed(Bundle resultData) { + mConfigState.setAction(PROVIDER_NOT_SET); + preferences.edit().remove(Provider.KEY).apply(); + + setResult(RESULT_CANCELED, mConfigState); + + String reasonToFail = resultData.getString(ERRORS); + showDownloadFailedDialog(reasonToFail); + } + + void handleCorrectlyDownloadedCertificate() { + mProgressBar.incrementProgressBy(1); + hideProgressBar(); + showProviderDetails(); + } + + void handleIncorrectlyDownloadedCertificate() { + mConfigState.setAction(PROVIDER_NOT_SET); + hideProgressBar(); + setResult(RESULT_CANCELED, mConfigState); + } + + @Override + public void onReceiveResult(int resultCode, Bundle resultData) { + if (resultCode == ProviderAPI.PROVIDER_OK) { + handleProviderSetUp(); } else if (resultCode == AboutFragment.VIEWED) { // Do nothing, right now // I need this for CW to wait for the About activity to end before going back to Dashboard. @@ -274,7 +288,6 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity @OnItemClick(R.id.provider_list) void onItemSelected(int position) { if (SETTING_UP_PROVIDER.equals(mConfigState.getAction()) || - PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction()) || PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction())) { return; } @@ -294,7 +307,6 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity @Override public void onBackPressed() { if (SETTING_UP_PROVIDER.equals(mConfigState.getAction()) || - PENDING_SHOW_PROVIDER_DETAILS.equals(mConfigState.getAction()) || PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction())) { stopSettingUpProvider(); } else { @@ -326,7 +338,6 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity Intent providerAPICommand = new Intent(this, ProviderAPI.class); providerAPICommand.setAction(ProviderAPI.UPDATE_PROVIDER_DETAILS); - providerAPICommand.putExtra(ProviderAPI.RECEIVER_KEY, providerAPIResultReceiver); Bundle parameters = new Bundle(); parameters.putString(Provider.MAIN_URL, selectedProvider.getMainUrl().toString()); providerAPICommand.putExtra(ProviderAPI.PARAMETERS, parameters); @@ -334,6 +345,13 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity startService(providerAPICommand); } + public void checkProviderSetUp() { + Intent providerAPICommand = new Intent(this, ProviderAPI.class); + providerAPICommand.setAction(PROVIDER_SET_UP); + providerAPICommand.putExtra(ProviderAPI.RECEIVER_KEY, providerAPIResultReceiver); + startService(providerAPICommand); + } + private void askDashboardToQuitApp() { Intent askQuit = new Intent(); askQuit.putExtra(APP_ACTION_QUIT, APP_ACTION_QUIT); @@ -373,10 +391,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity */ private void downloadVpnCertificate() { Intent providerAPICommand = new Intent(this, ProviderAPI.class); - providerAPICommand.setAction(ProviderAPI.DOWNLOAD_CERTIFICATE); - providerAPICommand.putExtra(ProviderAPI.RECEIVER_KEY, providerAPIResultReceiver); - startService(providerAPICommand); } @@ -404,7 +419,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity /** * Shows an error dialog, if configuring of a provider failed. * - * @param reasonToFail + * @param reasonToFail - the reason it has failed */ public void showDownloadFailedDialog(String reasonToFail) { try { @@ -435,14 +450,11 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity */ public void showProviderDetails() { // show only if current activity is shown - if (isActivityShowing) { + if (isActivityShowing && !mConfigState.getAction().equalsIgnoreCase(SHOWING_PROVIDER_DETAILS)) { mConfigState.setAction(SHOWING_PROVIDER_DETAILS); Intent intent = new Intent(this, ProviderDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); - } else { - // may be called AFTER onSaveInstanceState (!) - mConfigState.setAction(PENDING_SHOW_PROVIDER_DETAILS); } } @@ -475,8 +487,34 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity public class ProviderAPIBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - int update = intent.getIntExtra(ProviderAPI.CURRENT_PROGRESS, 0); - mProgressBar.setProgress(update); + String action = intent.getAction(); + + if (action == null) { + return; + } + + if (action.equalsIgnoreCase(UPDATE_PROGRESSBAR)) { + int update = intent.getIntExtra(ProviderAPI.CURRENT_PROGRESS, 0); + mProgressBar.setProgress(update); + } else if (action.equalsIgnoreCase(PROVIDER_API_EVENT)) { + int resultCode = intent.getIntExtra(RESULT_CODE, -1); + + switch (resultCode) { + case PROVIDER_OK: + handleProviderSetUp(); + break; + case PROVIDER_NOK: + handleProviderSetupFailed((Bundle) intent.getParcelableExtra(RESULT_KEY)); + break; + case CORRECTLY_DOWNLOADED_CERTIFICATE: + handleCorrectlyDownloadedCertificate(); + break; + case INCORRECTLY_DOWNLOADED_CERTIFICATE: + handleIncorrectlyDownloadedCertificate(); + break; + + } + } } } } diff --git a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java index 901dee89..82ff9db8 100644 --- a/app/src/main/java/se/leap/bitmaskclient/Dashboard.java +++ b/app/src/main/java/se/leap/bitmaskclient/Dashboard.java @@ -274,7 +274,7 @@ public class Dashboard extends ButterKnifeActivity { .setPositiveButton(getResources().getString(R.string.setup_error_configure_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - startActivityForResult(new Intent(getApplicationContext(), ConfigurationWizard.class), REQUEST_CODE_CONFIGURE_LEAP); + startActivityForResult(new Intent(Dashboard.this, ConfigurationWizard.class), REQUEST_CODE_CONFIGURE_LEAP); } }) .setNegativeButton(getResources().getString(R.string.setup_error_close_button), new DialogInterface.OnClickListener() { diff --git a/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java b/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java index 1b36d807..a5cbf5f5 100644 --- a/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/LoginActivity.java @@ -2,6 +2,7 @@ package se.leap.bitmaskclient; import android.os.Bundle; import android.support.annotation.Nullable; +import android.util.Log; import butterknife.OnClick; @@ -20,6 +21,11 @@ public class LoginActivity extends ProviderCredentialsBaseActivity { setProviderHeaderLogo(R.drawable.mask); } + @Override + protected void onResume() { + super.onResume(); + } + @Override @OnClick(R.id.button) void handleButton() { diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java b/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java index 3dc93539..ccc71a67 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderAPI.java @@ -47,12 +47,15 @@ public class ProviderAPI extends IntentService implements ProviderApiManagerBase DOWNLOAD_CERTIFICATE = "downloadUserAuthedCertificate", PARAMETERS = "parameters", RESULT_KEY = "result", + RESULT_CODE = "RESULT CODE", RECEIVER_KEY = "receiver", ERRORS = "errors", ERRORID = "errorId", UPDATE_PROGRESSBAR = "update_progressbar", CURRENT_PROGRESS = "current_progress", - DOWNLOAD_EIP_SERVICE = TAG + ".DOWNLOAD_EIP_SERVICE"; + DOWNLOAD_EIP_SERVICE = TAG + ".DOWNLOAD_EIP_SERVICE", + PROVIDER_SET_UP = TAG + ".PROVIDER_SET_UP", + PROVIDER_API_EVENT = "PROVIDER_API_EVENT"; final public static int SUCCESSFUL_LOGIN = 3, @@ -106,7 +109,7 @@ public class ProviderAPI extends IntentService implements ProviderApiManagerBase } @Override - public void broadcastProgress(Intent intent) { + public void broadcastEvent(Intent intent) { sendBroadcast(intent); } diff --git a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java index 2542759f..da2e4c8b 100644 --- a/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java +++ b/app/src/main/java/se/leap/bitmaskclient/ProviderApiManagerBase.java @@ -73,6 +73,8 @@ import static se.leap.bitmaskclient.ProviderAPI.FAILED_LOGIN; import static se.leap.bitmaskclient.ProviderAPI.FAILED_SIGNUP; import static se.leap.bitmaskclient.ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE; import static se.leap.bitmaskclient.ProviderAPI.INCORRECTLY_DOWNLOADED_EIP_SERVICE; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_API_EVENT; +import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_SET_UP; import static se.leap.bitmaskclient.ProviderAPI.LOGOUT_FAILED; import static se.leap.bitmaskclient.ProviderAPI.LOG_IN; import static se.leap.bitmaskclient.ProviderAPI.LOG_OUT; @@ -80,6 +82,7 @@ import static se.leap.bitmaskclient.ProviderAPI.PARAMETERS; import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_NOK; import static se.leap.bitmaskclient.ProviderAPI.PROVIDER_OK; import static se.leap.bitmaskclient.ProviderAPI.RECEIVER_KEY; +import static se.leap.bitmaskclient.ProviderAPI.RESULT_CODE; import static se.leap.bitmaskclient.ProviderAPI.RESULT_KEY; import static se.leap.bitmaskclient.ProviderAPI.SET_UP_PROVIDER; import static se.leap.bitmaskclient.ProviderAPI.SIGN_UP; @@ -93,6 +96,7 @@ import static se.leap.bitmaskclient.R.string.error_io_exception_user_message; import static se.leap.bitmaskclient.R.string.error_json_exception_user_message; import static se.leap.bitmaskclient.R.string.error_no_such_algorithm_exception_user_message; import static se.leap.bitmaskclient.R.string.malformed_url; +import static se.leap.bitmaskclient.R.string.routes_info_excl; import static se.leap.bitmaskclient.R.string.server_unreachable_message; import static se.leap.bitmaskclient.R.string.service_is_down_error; import static se.leap.bitmaskclient.R.string.warning_corrupted_provider_cert; @@ -107,7 +111,7 @@ import static se.leap.bitmaskclient.R.string.warning_expired_provider_cert; public abstract class ProviderApiManagerBase { public interface ProviderApiServiceCallback { - void broadcastProgress(Intent intent); + void broadcastEvent(Intent intent); } private ProviderApiServiceCallback serviceCallback; @@ -171,50 +175,56 @@ public abstract class ProviderApiManagerBase { Bundle result = setUpProvider(parameters); if (go_ahead) { if (result.getBoolean(RESULT_KEY)) { - receiver.send(PROVIDER_OK, result); + sendToReceiverOrBroadcast(receiver, PROVIDER_OK, result); } else { - receiver.send(PROVIDER_NOK, result); + sendToReceiverOrBroadcast(receiver, PROVIDER_NOK, result); } } } else if (action.equalsIgnoreCase(SIGN_UP)) { UserStatus.updateStatus(UserStatus.SessionStatus.SIGNING_UP, resources); Bundle result = tryToRegister(parameters); if (result.getBoolean(RESULT_KEY)) { - receiver.send(SUCCESSFUL_SIGNUP, result); + sendToReceiverOrBroadcast(receiver, SUCCESSFUL_SIGNUP, result); } else { - receiver.send(FAILED_SIGNUP, result); + sendToReceiverOrBroadcast(receiver, FAILED_SIGNUP, result); } } else if (action.equalsIgnoreCase(LOG_IN)) { UserStatus.updateStatus(UserStatus.SessionStatus.LOGGING_IN, resources); Bundle result = tryToAuthenticate(parameters); if (result.getBoolean(RESULT_KEY)) { - receiver.send(SUCCESSFUL_LOGIN, result); + sendToReceiverOrBroadcast(receiver, SUCCESSFUL_LOGIN, result); UserStatus.updateStatus(UserStatus.SessionStatus.LOGGED_IN, resources); } else { - receiver.send(FAILED_LOGIN, result); + sendToReceiverOrBroadcast(receiver, FAILED_LOGIN, result); UserStatus.updateStatus(UserStatus.SessionStatus.NOT_LOGGED_IN, resources); } } else if (action.equalsIgnoreCase(LOG_OUT)) { UserStatus.updateStatus(UserStatus.SessionStatus.LOGGING_OUT, resources); if (logOut()) { - receiver.send(SUCCESSFUL_LOGOUT, Bundle.EMPTY); + sendToReceiverOrBroadcast(receiver, SUCCESSFUL_LOGOUT, Bundle.EMPTY); UserStatus.updateStatus(UserStatus.SessionStatus.LOGGED_OUT, resources); } else { - receiver.send(LOGOUT_FAILED, Bundle.EMPTY); + sendToReceiverOrBroadcast(receiver, LOGOUT_FAILED, Bundle.EMPTY); UserStatus.updateStatus(UserStatus.SessionStatus.DIDNT_LOG_OUT, resources); } } else if (action.equalsIgnoreCase(DOWNLOAD_CERTIFICATE)) { if (updateVpnCertificate()) { - receiver.send(CORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); + sendToReceiverOrBroadcast(receiver, CORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); } else { - receiver.send(INCORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); + sendToReceiverOrBroadcast(receiver, INCORRECTLY_DOWNLOADED_CERTIFICATE, Bundle.EMPTY); } } else if (action.equalsIgnoreCase(DOWNLOAD_EIP_SERVICE)) { Bundle result = getAndSetEipServiceJson(); if (result.getBoolean(RESULT_KEY)) { - receiver.send(CORRECTLY_DOWNLOADED_EIP_SERVICE, result); + sendToReceiverOrBroadcast(receiver, CORRECTLY_DOWNLOADED_EIP_SERVICE, result); } else { - receiver.send(INCORRECTLY_DOWNLOADED_EIP_SERVICE, result); + sendToReceiverOrBroadcast(receiver, INCORRECTLY_DOWNLOADED_EIP_SERVICE, result); + } + } else if (action.equalsIgnoreCase(PROVIDER_SET_UP)) { + if(EIP_SERVICE_JSON_DOWNLOADED && CA_CERT_DOWNLOADED && PROVIDER_JSON_DOWNLOADED ) { + if(receiver!= null) { + receiver.send(PROVIDER_OK, Bundle.EMPTY); + } } } } @@ -421,20 +431,36 @@ public abstract class ProviderApiManagerBase { return userNotificationBundle; } + void sendToReceiverOrBroadcast(ResultReceiver receiver, int resultCode, Bundle resultData) { + if (receiver != null) { + receiver.send(resultCode, resultData); + } else { + broadcastEvent(PROVIDER_API_EVENT, resultCode, resultData); + } + } + /** * Sets up an intent with the progress value passed as a parameter * and sends it as a broadcast. * * @param progress */ - protected void broadcastProgress(int progress) { - Intent intentUpdate = new Intent(); - intentUpdate.setAction(UPDATE_PROGRESSBAR); + void broadcastProgress(int progress) { + Intent intentUpdate = new Intent(UPDATE_PROGRESSBAR); intentUpdate.addCategory(Intent.CATEGORY_DEFAULT); intentUpdate.putExtra(CURRENT_PROGRESS, progress); - serviceCallback.broadcastProgress(intentUpdate); + serviceCallback.broadcastEvent(intentUpdate); } + void broadcastEvent(String action, int resultCode , Bundle resultData) { + Intent intentUpdate = new Intent(action); + intentUpdate.addCategory(Intent.CATEGORY_DEFAULT); + intentUpdate.putExtra(RESULT_CODE, resultCode); + intentUpdate.putExtra(RESULT_KEY, resultData); + serviceCallback.broadcastEvent(intentUpdate); + } + + /** * Validates parameters entered by the user to log in * -- cgit v1.2.3 From df1e68c672de71633e99234360ea92d77e67a86d Mon Sep 17 00:00:00 2001 From: Fup Duck Date: Tue, 16 Jan 2018 18:31:37 +0100 Subject: corretly handle dialog on orientation change --- .../bitmaskclient/BaseConfigurationWizard.java | 25 ++++++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java index 64ea4779..d0868437 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java +++ b/app/src/main/java/se/leap/bitmaskclient/BaseConfigurationWizard.java @@ -118,6 +118,7 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity //TODO: add some states (values for progressbarText) about ongoing setup or remove that field private boolean isActivityShowing; + private String reasonToFail; public abstract void retrySetUpProvider(); @@ -140,6 +141,13 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity outState.putString(PROGRESSBAR_TEXT, progressbarDescription.getText().toString()); outState.putString(ACTIVITY_STATE, mConfigState.getAction()); outState.putParcelable(Provider.KEY, selectedProvider); + + DialogFragment dialogFragment = (DialogFragment) fragmentManager.findFragmentByTag(DownloadFailedDialog.TAG); + if (dialogFragment != null) { + outState.putString(REASON_TO_FAIL, reasonToFail); + dialogFragment.dismiss(); + } + super.onSaveInstanceState(outState); } @@ -160,9 +168,15 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity } private void restoreState(Bundle savedInstanceState) { + selectedProvider = savedInstanceState.getParcelable(Provider.KEY); mConfigState.setAction(savedInstanceState.getString(ACTIVITY_STATE, PROVIDER_NOT_SET)); + reasonToFail = savedInstanceState.getString(REASON_TO_FAIL); + if(reasonToFail != null) { + showDownloadFailedDialog(); + } + if (SETTING_UP_PROVIDER.equals(mConfigState.getAction()) || PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction()) ) { @@ -180,9 +194,8 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity showProgressBar(); adapter.hideAllBut(adapter.indexOf(selectedProvider)); checkProviderSetUp(); - showDownloadFailedDialog(null); } else if (PENDING_SHOW_FAILED_DIALOG.equals(mConfigState.getAction())) { - showDownloadFailedDialog(mConfigState.getStringExtra(REASON_TO_FAIL)); + showDownloadFailedDialog(); } else if (SHOWING_PROVIDER_DETAILS.equals(mConfigState.getAction())) { cancelAndShowAllProviders(); } @@ -259,8 +272,8 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity setResult(RESULT_CANCELED, mConfigState); - String reasonToFail = resultData.getString(ERRORS); - showDownloadFailedDialog(reasonToFail); + reasonToFail = resultData.getString(ERRORS); + showDownloadFailedDialog(); } void handleCorrectlyDownloadedCertificate() { @@ -418,10 +431,8 @@ public abstract class BaseConfigurationWizard extends ButterKnifeActivity /** * Shows an error dialog, if configuring of a provider failed. - * - * @param reasonToFail - the reason it has failed */ - public void showDownloadFailedDialog(String reasonToFail) { + public void showDownloadFailedDialog() { try { FragmentTransaction fragmentTransaction = fragmentManager.removePreviousFragment(DownloadFailedDialog.TAG); DialogFragment newFragment; -- cgit v1.2.3 From 76884123b22dbdd7538add0d931c5f2d8e660ed2 Mon Sep 17 00:00:00 2001 From: cyBerta Date: Tue, 16 Jan 2018 13:59:33 +0100 Subject: #8788 implement VpnNotificationManager to handle notifications from VoidVPN and OpenVPN --- .../java/se/leap/bitmaskclient/BitmaskApp.java | 46 --- .../leap/bitmaskclient/VpnNotificationManager.java | 308 +++++++++++++++++++++ .../se/leap/bitmaskclient/eip/VoidVpnService.java | 139 +++------- 3 files changed, 341 insertions(+), 152 deletions(-) create mode 100644 app/src/main/java/se/leap/bitmaskclient/VpnNotificationManager.java (limited to 'app/src/main/java/se/leap/bitmaskclient') diff --git a/app/src/main/java/se/leap/bitmaskclient/BitmaskApp.java b/app/src/main/java/se/leap/bitmaskclient/BitmaskApp.java index d7f574b2..88a01b62 100644 --- a/app/src/main/java/se/leap/bitmaskclient/BitmaskApp.java +++ b/app/src/main/java/se/leap/bitmaskclient/BitmaskApp.java @@ -1,16 +1,6 @@ package se.leap.bitmaskclient; -import android.annotation.TargetApi; import android.app.Application; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.content.Context; -import android.graphics.Color; -import android.os.Build; - -import de.blinkt.openvpn.core.OpenVPNService; - -import static android.os.Build.VERSION_CODES.O; /** * Created by cyberta on 24.10.17. @@ -23,42 +13,6 @@ public class BitmaskApp extends Application { super.onCreate(); PRNGFixes.apply(); //TODO: add LeakCanary! - if (Build.VERSION.SDK_INT >= O) - createNotificationChannelsForOpenvpn(); - } - - - @TargetApi(O) - private void createNotificationChannelsForOpenvpn() { - NotificationManager mNotificationManager = - (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - - // Background message - CharSequence name = getString(R.string.channel_name_background); - NotificationChannel mChannel = new NotificationChannel(OpenVPNService.NOTIFICATION_CHANNEL_BG_ID, - name, NotificationManager.IMPORTANCE_MIN); - - mChannel.setDescription(getString(R.string.channel_description_background)); - mChannel.enableLights(false); - - mChannel.setLightColor(Color.DKGRAY); - mNotificationManager.createNotificationChannel(mChannel); - - // Connection status change messages - - name = getString(R.string.channel_name_status); - mChannel = new NotificationChannel(OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID, - name, NotificationManager.IMPORTANCE_DEFAULT); - - - mChannel.setDescription(getString(R.string.channel_description_status)); - mChannel.enableLights(true); - - mChannel.setLightColor(Color.BLUE); - mNotificationManager.createNotificationChannel(mChannel); - } - - } diff --git a/app/src/main/java/se/leap/bitmaskclient/VpnNotificationManager.java b/app/src/main/java/se/leap/bitmaskclient/VpnNotificationManager.java new file mode 100644 index 00000000..5b089524 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/VpnNotificationManager.java @@ -0,0 +1,308 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program 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. + * + * This program is distributed in the hope that it will be useful, + * 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 + * along with this program. If not, see . + */ +package se.leap.bitmaskclient; + +import android.annotation.TargetApi; +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.graphics.Color; +import android.os.Build; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.NotificationCompat; +import android.support.v4.app.NotificationManagerCompat; +import android.widget.RemoteViews; + +import de.blinkt.openvpn.LaunchVPN; +import de.blinkt.openvpn.core.ConnectionStatus; +import de.blinkt.openvpn.core.OpenVPNService; +import se.leap.bitmaskclient.eip.VoidVpnService; + +import static android.os.Build.VERSION_CODES.O; +import static android.support.v4.app.NotificationCompat.PRIORITY_HIGH; +import static android.support.v4.app.NotificationCompat.PRIORITY_MAX; +import static android.support.v4.app.NotificationCompat.PRIORITY_MIN; +import static android.text.TextUtils.isEmpty; +import static de.blinkt.openvpn.core.ConnectionStatus.LEVEL_NONETWORK; +import static de.blinkt.openvpn.core.ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT; +import static se.leap.bitmaskclient.Constants.EIP_ACTION_STOP_BLOCKING_VPN; + +/** + * Created by cyberta on 14.01.18. + */ + +public class VpnNotificationManager { + + Context context; + private VpnServiceCallback vpnServiceCallback; + private NotificationManager notificationManager; + private NotificationManagerCompat compatNotificationManager; + private String[] notificationChannels = { + OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID, + OpenVPNService.NOTIFICATION_CHANNEL_BG_ID, + VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID}; + private String lastNotificationChannel = ""; + + public interface VpnServiceCallback { + void onNotificationBuild(int notificationId, Notification notification); + void onNotificationStop(); + } + + public VpnNotificationManager(@NonNull Context context, @NonNull VpnServiceCallback vpnServiceCallback) { + this.context = context; + notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + compatNotificationManager = NotificationManagerCompat.from(context); + this.vpnServiceCallback = vpnServiceCallback; + } + + public void buildVoidVpnNotification(final String msg, String tickerText, ConnectionStatus status) { + //TODO: implement extra Dashboard.ACTION_ASK_TO_CANCEL_BLOCKING_VPN + NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(R.drawable.ic_menu_close_clear_cancel, + context.getString(R.string.vpn_button_turn_off_blocking), getStopVoidVpnIntent()); + + buildVpnNotification( + context.getString(R.string.void_vpn_title), + msg, + tickerText, + status, + VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID, + PRIORITY_MAX, + 0, + getDashboardIntent(), + actionBuilder.build()); + } + + public void stopNotifications(String notificationChannelNewstatusId) { + vpnServiceCallback.onNotificationStop(); + compatNotificationManager.cancel(notificationChannelNewstatusId.hashCode()); + } + + public void deleteNotificationChannel(String notificationChannel) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && + notificationManager.getNotificationChannel(notificationChannel) != null) { + notificationManager.deleteNotificationChannel(notificationChannel); + } + } + + /** + * @param msg + * @param tickerText + * @param status + * @param when + */ + public void buildOpenVpnNotification(String profileName, final String msg, String tickerText, ConnectionStatus status, long when, String notificationChannelNewstatusId) { + NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action. + Builder(R.drawable.ic_menu_close_clear_cancel, context.getString(R.string.cancel_connection), getDisconnectIntent()); + String title; + if (isEmpty(profileName)) { + title = context.getString(R.string.app_name); + } else { + title = context.getString(R.string.notifcation_title_bitmask, profileName); + } + + PendingIntent contentIntent; + if (status == LEVEL_WAITING_FOR_USER_INPUT) + contentIntent = getUserInputIntent(msg); + else + contentIntent = getDashboardIntent(); + + int priority; + if (OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID.equals(notificationChannelNewstatusId)) { + priority = PRIORITY_HIGH; + } else { + // background channel + priority = PRIORITY_MIN; + } + + buildVpnNotification( + title, + msg, + tickerText, + status, + notificationChannelNewstatusId, + priority, + when, + contentIntent, + actionBuilder.build()); + } + + + @TargetApi(O) + public void createVoidVpnNotificationChannel() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return; + } + + // Connection status change messages + CharSequence name = context.getString(R.string.channel_name_status); + NotificationChannel mChannel = new NotificationChannel(VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID, + name, NotificationManager.IMPORTANCE_DEFAULT); + + mChannel.setDescription(context.getString(R.string.channel_description_status)); + mChannel.enableLights(true); + + mChannel.setLightColor(Color.BLUE); + notificationManager.createNotificationChannel(mChannel); + } + + @TargetApi(O) + public void createOpenVpnNotificationChannel() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return; + } + + // Background message + CharSequence name = context.getString(R.string.channel_name_background); + NotificationChannel mChannel = new NotificationChannel(OpenVPNService.NOTIFICATION_CHANNEL_BG_ID, + name, NotificationManager.IMPORTANCE_MIN); + + mChannel.setDescription(context.getString(R.string.channel_description_background)); + mChannel.enableLights(false); + + mChannel.setLightColor(Color.DKGRAY); + notificationManager.createNotificationChannel(mChannel); + + // Connection status change messages + name = context.getString(R.string.channel_name_status); + mChannel = new NotificationChannel(OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID, + name, NotificationManager.IMPORTANCE_DEFAULT); + + + mChannel.setDescription(context.getString(R.string.channel_description_status)); + mChannel.enableLights(true); + + mChannel.setLightColor(Color.BLUE); + notificationManager.createNotificationChannel(mChannel); + } + + /** + * @return a custom remote view for notifications for API 16 - 19 + */ + private RemoteViews getKitkatCustomRemoteView(ConnectionStatus status, String title, String message) { + int iconResource = getIconByConnectionStatus(status); + RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout); + remoteViews.setImageViewResource(R.id.image_icon, iconResource); + remoteViews.setTextViewText(R.id.message, message); + remoteViews.setTextViewText(R.id.title, title); + + return remoteViews; + } + + private void buildVpnNotification(String title, final String msg, String tickerText, ConnectionStatus status, String notificationChannelNewstatusId, int priority, long when, PendingIntent contentIntent, NotificationCompat.Action notificationAction) { + NotificationCompat.Builder nCompatBuilder = new NotificationCompat.Builder(context, notificationChannelNewstatusId); + int icon = getIconByConnectionStatus(status); + + // this is a workaround to avoid confusion between the Android's system vpn notification + // showing a filled out key icon and the bitmask icon indicating a different state. + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT && + notificationChannelNewstatusId.equals(OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID) && + status != LEVEL_NONETWORK + ) { + // removes the icon from the system status bar + icon = android.R.color.transparent; + // adds the icon to the notification in the notification drawer + nCompatBuilder.setContent(getKitkatCustomRemoteView(status, title, msg)); + } else { + nCompatBuilder.addAction(notificationAction); + } + + nCompatBuilder.setContentTitle(title); + nCompatBuilder.setCategory(NotificationCompat.CATEGORY_SERVICE); + nCompatBuilder.setLocalOnly(true); + nCompatBuilder.setContentText(msg); + nCompatBuilder.setOnlyAlertOnce(true); + nCompatBuilder.setSmallIcon(icon); + nCompatBuilder.setPriority(priority); + nCompatBuilder.setOngoing(true); + nCompatBuilder.setUsesChronometer(true); + nCompatBuilder.setWhen(when); + nCompatBuilder.setContentIntent(contentIntent); + if (!isEmpty(tickerText)) { + nCompatBuilder.setTicker(tickerText); + } + + Notification notification = nCompatBuilder.build(); + int notificationId = notificationChannelNewstatusId.hashCode(); + + if (!notificationChannelNewstatusId.equals(lastNotificationChannel)) { + // Cancel old notification + for (String channel : notificationChannels) { + stopNotifications(channel); + } + } + + compatNotificationManager.notify(notificationId, notification); + vpnServiceCallback.onNotificationBuild(notificationId, notification); + lastNotificationChannel = notificationChannelNewstatusId; + } + + private PendingIntent getDashboardIntent() { + Intent startDashboard = new Intent(context, Dashboard.class); + startDashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | + Intent.FLAG_ACTIVITY_SINGLE_TOP); + return PendingIntent.getActivity(context, 0, startDashboard, PendingIntent.FLAG_CANCEL_CURRENT); + } + + private PendingIntent getStopVoidVpnIntent() { + Intent stopVoidVpnIntent = new Intent (context, VoidVpnService.class); + stopVoidVpnIntent.setAction(EIP_ACTION_STOP_BLOCKING_VPN); + return PendingIntent.getService(context, 0, stopVoidVpnIntent, PendingIntent.FLAG_CANCEL_CURRENT); + } + + private PendingIntent getDisconnectIntent() { + Intent disconnectVPN = new Intent(context, Dashboard.class); + disconnectVPN.setAction(Intent.ACTION_MAIN); //needs to be set that actual action can get triggered + disconnectVPN.putExtra(Dashboard.ACTION_ASK_TO_CANCEL_VPN, true); + disconnectVPN.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); + return PendingIntent.getActivity(context, 0, disconnectVPN, PendingIntent.FLAG_CANCEL_CURRENT); + } + + private PendingIntent getUserInputIntent(String needed) { + Intent intent = new Intent(context, LaunchVPN.class); + intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); + intent.putExtra("need", needed); + Bundle b = new Bundle(); + b.putString("need", needed); + PendingIntent pIntent = PendingIntent.getActivity(context, 12, intent, 0); + return pIntent; + } + + private int getIconByConnectionStatus(ConnectionStatus level) { + switch (level) { + case LEVEL_CONNECTED: + return R.drawable.ic_stat_vpn; + case LEVEL_AUTH_FAILED: + case LEVEL_NONETWORK: + case LEVEL_NOTCONNECTED: + return R.drawable.ic_stat_vpn_offline; + case LEVEL_CONNECTING_NO_SERVER_REPLY_YET: + case LEVEL_WAITING_FOR_USER_INPUT: + case LEVEL_CONNECTING_SERVER_REPLIED: + return R.drawable.ic_stat_vpn_outline; + case LEVEL_BLOCKING: + return R.drawable.ic_stat_vpn_blocking; + case UNKNOWN_LEVEL: + default: + return R.drawable.ic_stat_vpn_offline; + } + } + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java index 792de2cb..6d49d83d 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/VoidVpnService.java @@ -1,19 +1,27 @@ +/** + * Copyright (c) 2013 LEAP Encryption Access Project and contributers + * + * This program 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. + * + * This program is distributed in the hope that it will be useful, + * 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 + * along with this program. If not, see . + */ package se.leap.bitmaskclient.eip; -import android.annotation.TargetApi; import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.graphics.Color; import android.net.VpnService; import android.os.Build; import android.os.ParcelFileDescriptor; -import android.support.v4.app.NotificationCompat; -import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import java.io.IOException; @@ -22,10 +30,9 @@ import java.util.Observer; import de.blinkt.openvpn.core.ConnectionStatus; import de.blinkt.openvpn.core.VpnStatus; -import se.leap.bitmaskclient.Dashboard; import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.VpnNotificationManager; -import static android.os.Build.VERSION_CODES.O; import static se.leap.bitmaskclient.Constants.EIP_ACTION_START_ALWAYS_ON_EIP; import static se.leap.bitmaskclient.Constants.EIP_ACTION_START_BLOCKING_VPN; import static se.leap.bitmaskclient.Constants.EIP_ACTION_STOP_BLOCKING_VPN; @@ -33,7 +40,7 @@ import static se.leap.bitmaskclient.Constants.EIP_IS_ALWAYS_ON; import static se.leap.bitmaskclient.Constants.SHARED_PREFERENCES; -public class VoidVpnService extends VpnService implements Observer { +public class VoidVpnService extends VpnService implements Observer, VpnNotificationManager.VpnServiceCallback { static final String TAG = VoidVpnService.class.getSimpleName(); static ParcelFileDescriptor fd; @@ -42,16 +49,15 @@ public class VoidVpnService extends VpnService implements Observer { private static final String STATE_ESTABLISH = "ESTABLISHVOIDVPN"; public static final String NOTIFICATION_CHANNEL_NEWSTATUS_ID = "bitmask_void_vpn_news"; private EipStatus eipStatus; - NotificationManager notificationManager; - NotificationManagerCompat compatNotificationManager; + private VpnNotificationManager notificationManager; @Override public void onCreate() { super.onCreate(); - notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - compatNotificationManager = NotificationManagerCompat.from(this); eipStatus = EipStatus.getInstance(); eipStatus.addObserver(this); + notificationManager = new VpnNotificationManager(this, this); + notificationManager.createVoidVpnNotificationChannel(); } @Override @@ -91,24 +97,9 @@ public class VoidVpnService extends VpnService implements Observer { closeFd(); } - @TargetApi(O) - private void createNotificationChannel() { - - // Connection status change messages - CharSequence name = getString(R.string.channel_name_status); - NotificationChannel mChannel = new NotificationChannel(VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID, - name, NotificationManagerCompat.IMPORTANCE_DEFAULT); - - mChannel.setDescription(getString(R.string.channel_description_status)); - mChannel.enableLights(true); - - mChannel.setLightColor(Color.BLUE); - notificationManager.createNotificationChannel(mChannel); - } - - private void stop() { - stopNotifications(); + notificationManager.stopNotifications(NOTIFICATION_CHANNEL_NEWSTATUS_ID); + notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_NEWSTATUS_ID); if (thread != null) { thread.interrupt(); } @@ -174,87 +165,23 @@ public class VoidVpnService extends VpnService implements Observer { } if (eipStatus.isBlockingVpnEstablished()) { - showNotification(getString(eipStatus.getLocalizedResId()), - getString(eipStatus.getLocalizedResId()), eipStatus.getLevel()); + notificationManager.buildVoidVpnNotification( + getString(eipStatus.getLocalizedResId()), + getString(eipStatus.getLocalizedResId()), + eipStatus.getLevel()); } else { - stopNotifications(); + notificationManager.stopNotifications(NOTIFICATION_CHANNEL_NEWSTATUS_ID); } } - private void stopNotifications() { - stopForeground(true); - compatNotificationManager.cancel(NOTIFICATION_CHANNEL_NEWSTATUS_ID.hashCode()); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && - notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_NEWSTATUS_ID) != null) { - notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_NEWSTATUS_ID); - } - } - - /** - * @param msg - * @param tickerText - * @param status - */ - private void showNotification(final String msg, String tickerText, ConnectionStatus status) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - createNotificationChannel(); - } - - int icon = getIconByConnectionStatus(status); - NotificationCompat.Builder nCompatBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_NEWSTATUS_ID); - - nCompatBuilder.setContentTitle(getString(R.string.notifcation_title_bitmask, getString(R.string.void_vpn_title))); - nCompatBuilder.setCategory(NotificationCompat.CATEGORY_SERVICE); - nCompatBuilder.setLocalOnly(true); - nCompatBuilder.setContentText(msg); - nCompatBuilder.setOnlyAlertOnce(true); - nCompatBuilder.setSmallIcon(icon); - if (tickerText != null && !tickerText.equals("")) { - nCompatBuilder.setTicker(tickerText); - } - - nCompatBuilder.setContentIntent(getDashboardIntent()); - //TODO: implement extra Dashboard.ACTION_ASK_TO_CANCEL_BLOCKING_VPN - NotificationCompat.Action.Builder builder = new NotificationCompat.Action.Builder(R.drawable.ic_menu_close_clear_cancel, getString(R.string.vpn_button_turn_off_blocking), getStopVoidVpnIntent()); - nCompatBuilder.addAction(builder.build()); - - Notification notification = nCompatBuilder.build(); - int notificationId = NOTIFICATION_CHANNEL_NEWSTATUS_ID.hashCode(); - compatNotificationManager.notify(notificationId, notification); + @Override + public void onNotificationBuild(int notificationId, Notification notification) { startForeground(notificationId, notification); } - private PendingIntent getDashboardIntent() { - Intent startDashboard = new Intent(this, Dashboard.class); - startDashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | - Intent.FLAG_ACTIVITY_SINGLE_TOP); - return PendingIntent.getActivity(this, 0, startDashboard, PendingIntent.FLAG_CANCEL_CURRENT); - } - - private PendingIntent getStopVoidVpnIntent() { - Intent stopVoidVpnIntent = new Intent (this, VoidVpnService.class); - stopVoidVpnIntent.setAction(EIP_ACTION_STOP_BLOCKING_VPN); - return PendingIntent.getService(this, 0, stopVoidVpnIntent, PendingIntent.FLAG_CANCEL_CURRENT); + @Override + public void onNotificationStop() { + stopForeground(true); } - //TODO: replace with getIconByEipLevel(EipLevel level) - private int getIconByConnectionStatus(ConnectionStatus level) { - switch (level) { - case LEVEL_CONNECTED: - return R.drawable.ic_stat_vpn; - case LEVEL_AUTH_FAILED: - case LEVEL_NONETWORK: - case LEVEL_NOTCONNECTED: - return R.drawable.ic_stat_vpn_offline; - case LEVEL_CONNECTING_NO_SERVER_REPLY_YET: - case LEVEL_WAITING_FOR_USER_INPUT: - case LEVEL_CONNECTING_SERVER_REPLIED: - return R.drawable.ic_stat_vpn_outline; - case LEVEL_BLOCKING: - return R.drawable.ic_stat_vpn_blocking; - case UNKNOWN_LEVEL: - default: - return R.drawable.ic_stat_vpn_offline; - } - } } -- cgit v1.2.3