diff options
author | cyberta <cyberta@riseup.net> | 2021-11-24 09:26:40 +0000 |
---|---|---|
committer | cyberta <cyberta@riseup.net> | 2021-11-24 09:26:40 +0000 |
commit | 68ca9c827da3c3fad9e70c74960f113560fd6711 (patch) | |
tree | dda6f99c2ef2b222d4f07d0ef80d5d0cc373604e /app/src/main/java | |
parent | 9b2b57d8617e60c0b69713e1e5f14dbb8e57c70a (diff) | |
parent | e3cd28aa6ef16d9bde179a3e1117cdfa585939a4 (diff) |
Merge branch 'simply_secure_UI_changes' into 'master'
Gateway selection UI overhaul
Closes #9047
See merge request leap/bitmask_android!140
Diffstat (limited to 'app/src/main/java')
27 files changed, 1042 insertions, 305 deletions
diff --git a/app/src/main/java/de/blinkt/openvpn/core/OpenVPNService.java b/app/src/main/java/de/blinkt/openvpn/core/OpenVPNService.java index 9ed2054e..ae38a59b 100644 --- a/app/src/main/java/de/blinkt/openvpn/core/OpenVPNService.java +++ b/app/src/main/java/de/blinkt/openvpn/core/OpenVPNService.java @@ -377,6 +377,7 @@ public class OpenVPNService extends VpnService implements StateListener, Callbac // connections[n], n>0 gets choosen? Connection connection = mProfile.mConnections[0]; + VpnStatus.setCurrentlyConnectingProfile(mProfile); VpnStatus.logInfo(R.string.building_configration); VpnStatus.updateStateString("VPN_GENERATE_CONFIG", "", R.string.building_configration, ConnectionStatus.LEVEL_START); diff --git a/app/src/main/java/de/blinkt/openvpn/core/VpnStatus.java b/app/src/main/java/de/blinkt/openvpn/core/VpnStatus.java index 8007f7c5..4fa5a7b6 100644 --- a/app/src/main/java/de/blinkt/openvpn/core/VpnStatus.java +++ b/app/src/main/java/de/blinkt/openvpn/core/VpnStatus.java @@ -48,6 +48,7 @@ public class VpnStatus { final static java.lang.Object readFileLock = new Object(); private static VpnProfile lastConnectedProfile; + private static VpnProfile currentlyConnectingProfile; public static TrafficHistory trafficHistory; @@ -170,6 +171,15 @@ public class VpnStatus { } + public static void setCurrentlyConnectingProfile(VpnProfile connectingProfile) { + currentlyConnectingProfile = connectingProfile; + } + + public static String getCurrentlyConnectingVpnName() { + return currentlyConnectingProfile != null ? currentlyConnectingProfile.mName : null; + } + + public static String getLastConnectedVpnName() { return lastConnectedProfile != null ? lastConnectedProfile.mName : null; } @@ -531,4 +541,8 @@ public class VpnStatus { public static boolean isAlwaysOn() { return isAlwaysOnBooting.get(); } + + public static boolean isUsingBridges() { + return lastConnectedProfile != null && lastConnectedProfile.mUsePluggableTransports; + } } diff --git a/app/src/main/java/se/leap/bitmaskclient/base/MainActivity.java b/app/src/main/java/se/leap/bitmaskclient/base/MainActivity.java index 18ac8b7c..54977f0a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/MainActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/MainActivity.java @@ -60,6 +60,7 @@ import static se.leap.bitmaskclient.base.models.Constants.EIP_ACTION_LAUNCH_VPN; import static se.leap.bitmaskclient.base.models.Constants.EIP_ACTION_PREPARE_VPN; import static se.leap.bitmaskclient.base.models.Constants.EIP_ACTION_START; import static se.leap.bitmaskclient.base.models.Constants.EIP_REQUEST; +import static se.leap.bitmaskclient.base.models.Constants.LOCATION; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_KEY; import static se.leap.bitmaskclient.base.models.Constants.REQUEST_CODE_CONFIGURE_LEAP; import static se.leap.bitmaskclient.base.models.Constants.REQUEST_CODE_LOG_IN; @@ -85,6 +86,7 @@ public class MainActivity extends AppCompatActivity implements EipSetupListener, public final static String ACTION_SHOW_VPN_FRAGMENT = "action_show_vpn_fragment"; public final static String ACTION_SHOW_LOG_FRAGMENT = "action_show_log_fragment"; + public final static String ACTION_SHOW_DIALOG_FRAGMENT = "action_show_dialog_fragment"; /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. @@ -152,6 +154,13 @@ public class MainActivity extends AppCompatActivity implements EipSetupListener, fragment = new LogFragment(); setActionBarTitle(R.string.log_fragment_title); break; + case ACTION_SHOW_DIALOG_FRAGMENT: + if (intent.hasExtra(EIP.ERRORID)) { + String errorId = intent.getStringExtra(EIP.ERRORID); + String error = intent.getStringExtra(EIP.ERRORS); + String args = intent.getStringExtra(LOCATION); + showMainActivityErrorDialog(error, EIP.EIPErrors.valueOf(errorId), args); + } default: break; } @@ -324,12 +333,12 @@ public class MainActivity extends AppCompatActivity implements EipSetupListener, /** * Shows an error dialog */ - public void showMainActivityErrorDialog(String reasonToFail, EIP.EIPErrors error) { + public void showMainActivityErrorDialog(String reasonToFail, EIP.EIPErrors error, String... args) { try { FragmentTransaction fragmentTransaction = new FragmentManagerEnhanced( this.getSupportFragmentManager()).removePreviousFragment( MainActivityErrorDialog.TAG); - DialogFragment newFragment = MainActivityErrorDialog.newInstance(provider, reasonToFail, error); + DialogFragment newFragment = MainActivityErrorDialog.newInstance(provider, reasonToFail, error, args); newFragment.show(fragmentTransaction, MainActivityErrorDialog.TAG); } catch (IllegalStateException | NullPointerException e) { e.printStackTrace(); diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/AboutFragment.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/AboutFragment.java index c269c872..dbdd008a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/AboutFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/AboutFragment.java @@ -6,8 +6,8 @@ import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.TextView; +import androidx.appcompat.widget.AppCompatTextView; import androidx.fragment.app.Fragment; import butterknife.BindView; @@ -25,10 +25,10 @@ public class AboutFragment extends Fragment { private Unbinder unbinder; @BindView(R.id.version) - TextView versionTextView; + AppCompatTextView versionTextView; @BindView(R.id.terms_of_service) - TextView termsOfService; + AppCompatTextView termsOfService; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/EipFragment.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/EipFragment.java index 615221ae..e9300584 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/EipFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/EipFragment.java @@ -56,20 +56,26 @@ import de.blinkt.openvpn.core.ConnectionStatus; import de.blinkt.openvpn.core.IOpenVPNServiceInternal; import de.blinkt.openvpn.core.OpenVPNService; import de.blinkt.openvpn.core.VpnStatus; +import de.blinkt.openvpn.core.connection.Connection; +import se.leap.bitmaskclient.BuildConfig; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.base.FragmentManagerEnhanced; +import se.leap.bitmaskclient.base.MainActivity; import se.leap.bitmaskclient.base.models.Provider; import se.leap.bitmaskclient.base.models.ProviderObservable; -import se.leap.bitmaskclient.base.views.VpnStateImage; +import se.leap.bitmaskclient.base.utils.PreferenceHelper; +import se.leap.bitmaskclient.base.views.LocationButton; +import se.leap.bitmaskclient.base.views.MainButton; import se.leap.bitmaskclient.eip.EipCommand; import se.leap.bitmaskclient.eip.EipStatus; +import se.leap.bitmaskclient.eip.GatewaysManager; import se.leap.bitmaskclient.providersetup.ProviderAPICommand; import se.leap.bitmaskclient.providersetup.ProviderListActivity; import se.leap.bitmaskclient.providersetup.activities.CustomProviderSetupActivity; import se.leap.bitmaskclient.providersetup.activities.LoginActivity; import se.leap.bitmaskclient.providersetup.models.LeapSRPSession; -import static android.view.View.GONE; +import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; import static de.blinkt.openvpn.core.ConnectionStatus.LEVEL_NONETWORK; import static se.leap.bitmaskclient.R.string.vpn_certificate_user_message; @@ -83,9 +89,11 @@ import static se.leap.bitmaskclient.base.models.Constants.REQUEST_CODE_LOG_IN; import static se.leap.bitmaskclient.base.models.Constants.REQUEST_CODE_SWITCH_PROVIDER; import static se.leap.bitmaskclient.base.models.Constants.SHARED_PREFERENCES; import static se.leap.bitmaskclient.base.utils.ConfigHelper.isDefaultBitmask; +import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getPreferredCity; import static se.leap.bitmaskclient.base.utils.ViewHelper.convertDimensionToPx; import static se.leap.bitmaskclient.eip.EipSetupObserver.gatewayOrder; import static se.leap.bitmaskclient.eip.EipSetupObserver.reconnectingWithDifferentGateway; +import static se.leap.bitmaskclient.eip.GatewaysManager.Load.UNKNOWN; import static se.leap.bitmaskclient.providersetup.ProviderAPI.DOWNLOAD_GEOIP_JSON; import static se.leap.bitmaskclient.providersetup.ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE; import static se.leap.bitmaskclient.providersetup.ProviderAPI.USER_MESSAGE; @@ -101,21 +109,23 @@ public class EipFragment extends Fragment implements Observer { @BindView(R.id.background) AppCompatImageView background; - @BindView(R.id.vpn_state_image) - VpnStateImage vpnStateImage; + @BindView(R.id.main_button) + MainButton mainButton; - @BindView(R.id.vpn_main_button) - AppCompatButton mainButton; + @BindView(R.id.gateway_location_button) + LocationButton locationButton; - @BindView(R.id.routed_text) - AppCompatTextView routedText; + @BindView(R.id.main_description) + AppCompatTextView mainDescription; - @BindView(R.id.vpn_route) - AppCompatTextView vpnRoute; + @BindView(R.id.sub_description) + AppCompatTextView subDescription; private Unbinder unbinder; private EipStatus eipStatus; + private GatewaysManager gatewaysManager; + //---saved Instance ------- private final String KEY_SHOW_PENDING_START_CANCELLATION = "KEY_SHOW_PENDING_START_CANCELLATION"; private final String KEY_SHOW_ASK_TO_STOP_EIP = "KEY_SHOW_ASK_TO_STOP_EIP"; @@ -168,6 +178,10 @@ public class EipFragment extends Fragment implements Observer { } else { Log.e(TAG, "activity is null in onCreate - no preferences set!"); } + + gatewaysManager = new GatewaysManager(getContext()); + + } @Override @@ -189,6 +203,11 @@ public class EipFragment extends Fragment implements Observer { } restoreFromSavedInstance(savedInstanceState); + locationButton.setOnClickListener(v -> { + FragmentManagerEnhanced fragmentManager = new FragmentManagerEnhanced(getActivity().getSupportFragmentManager()); + Fragment fragment = new GatewaySelectionFragment(); + fragmentManager.replace(R.id.main_container, fragment, MainActivity.TAG); + }); return view; } @@ -252,16 +271,11 @@ public class EipFragment extends Fragment implements Observer { preferences.edit().putBoolean(EIP_RESTART_ON_BOOT, restartOnBoot).apply(); } - @OnClick(R.id.vpn_main_button) + @OnClick(R.id.main_button) void onButtonClick() { handleIcon(); } - @OnClick(R.id.vpn_state_image) - void onVpnStateImageClick() { - handleIcon(); - } - void handleIcon() { if (isOpenVpnRunningWithoutNetwork() || eipStatus.isConnected() || eipStatus.isConnecting()) handleSwitchOff(); @@ -307,8 +321,8 @@ public class EipFragment extends Fragment implements Observer { } private void setMainButtonEnabled(boolean enabled) { + locationButton.setEnabled(enabled); mainButton.setEnabled(enabled); - vpnStateImage.setEnabled(enabled); } public void startEipFromScratch() { @@ -401,58 +415,72 @@ public class EipFragment extends Fragment implements Observer { return; } - //Log.d(TAG, "eip fragment eipStatus state: " + eipStatus.getState() + " - level: " + eipStatus.getLevel() + " - is reconnecting: " + eipStatus.isReconnecting()); - - + Log.d(TAG, "eip fragment eipStatus state: " + eipStatus.getState() + " - level: " + eipStatus.getLevel() + " - is reconnecting: " + eipStatus.isReconnecting()); if (eipStatus.isConnecting() ) { setMainButtonEnabled(true); - showConnectingLayout(activity); - if (eipStatus.isReconnecting()) { - //Log.d(TAG, "eip show reconnecting toast!"); - //showReconnectToast(activity); - } - } else if (eipStatus.isConnected() ) { - mainButton.setText(activity.getString(R.string.vpn_button_turn_off)); + showConnectionTransitionLayout(true); + locationButton.setText(getString(R.string.finding_best_connection)); + locationButton.setLocationLoad(UNKNOWN); + locationButton.showBridgeIndicator(false); + locationButton.showRecommendedIndicator(false); + mainDescription.setText(R.string.eip_state_insecure); + subDescription.setText(null); + } else if (eipStatus.isConnected()) { setMainButtonEnabled(true); - vpnStateImage.setStateIcon(R.drawable.vpn_connected); - vpnStateImage.stopProgress(false); - routedText.setText(R.string.vpn_securely_routed); - routedText.setVisibility(VISIBLE); - vpnRoute.setVisibility(VISIBLE); - setVpnRouteText(); + mainButton.updateState(true, false, false); + Connection.TransportType transportType = PreferenceHelper.getUseBridges(getContext()) ? Connection.TransportType.OBFS4 : Connection.TransportType.OPENVPN; + locationButton.setLocationLoad(gatewaysManager.getLoadForLocation(VpnStatus.getLastConnectedVpnName(), transportType)); + locationButton.setText(VpnStatus.getLastConnectedVpnName()); + locationButton.showBridgeIndicator(VpnStatus.isUsingBridges()); + locationButton.showRecommendedIndicator(getPreferredCity(getContext())== null); + mainDescription.setText(R.string.eip_state_connected); + subDescription.setText(null); colorBackground(); } else if(isOpenVpnRunningWithoutNetwork()){ - mainButton.setText(activity.getString(R.string.vpn_button_turn_off)); + Log.d(TAG, "eip fragment eipStatus - isOpenVpnRunningWithoutNetwork"); setMainButtonEnabled(true); - vpnStateImage.setStateIcon(R.drawable.vpn_disconnected); - vpnStateImage.stopProgress(false); - routedText.setText(R.string.vpn_securely_routed_no_internet); - routedText.setVisibility(VISIBLE); - vpnRoute.setVisibility(VISIBLE); - setVpnRouteText(); + mainButton.updateState(true, false, true); + locationButton.setText(VpnStatus.getCurrentlyConnectingVpnName()); + locationButton.showBridgeIndicator(VpnStatus.isUsingBridges()); + locationButton.showBridgeIndicator(VpnStatus.isUsingBridges()); + locationButton.showRecommendedIndicator(getPreferredCity(getContext())== null); colorBackgroundALittle(); + mainDescription.setText(R.string.eip_state_connected); + subDescription.setText(R.string.eip_state_no_network); } else if (eipStatus.isDisconnected() && reconnectingWithDifferentGateway()) { - showConnectingLayout(activity); + showConnectionTransitionLayout(true); // showRetryToast(activity); + locationButton.setText(getString(R.string.finding_best_connection)); + locationButton.setLocationLoad(UNKNOWN); + locationButton.showBridgeIndicator(false); + locationButton.showRecommendedIndicator(false); + mainDescription.setText(R.string.eip_state_insecure); + subDescription.setText(R.string.reconnecting); } else if (eipStatus.isDisconnecting()) { setMainButtonEnabled(false); - showDisconnectingLayout(activity); + showConnectionTransitionLayout(false); + mainDescription.setText(R.string.eip_state_insecure); } else if (eipStatus.isBlocking()) { setMainButtonEnabled(true); - vpnStateImage.setStateIcon(R.drawable.vpn_blocking); - vpnStateImage.stopProgress(false); - routedText.setText(getString(R.string.void_vpn_establish, getString(R.string.app_name))); - routedText.setVisibility(VISIBLE); - vpnRoute.setVisibility(GONE); + mainButton.updateState(true, false, true); colorBackgroundALittle(); + locationButton.setText(getString(R.string.finding_best_connection)); + locationButton.setLocationLoad(UNKNOWN); + locationButton.showBridgeIndicator(false); + locationButton.showRecommendedIndicator(false); + mainDescription.setText(R.string.eip_state_connected); + subDescription.setText(getString(R.string.eip_state_blocking, getString(R.string.app_name))); } else { - mainButton.setText(activity.getString(R.string.vpn_button_turn_on)); + locationButton.setText(activity.getString(R.string.vpn_button_turn_on)); setMainButtonEnabled(true); - vpnStateImage.setStateIcon(R.drawable.vpn_disconnected); - vpnStateImage.stopProgress(false); - routedText.setVisibility(GONE); - vpnRoute.setVisibility(GONE); + mainButton.updateState(false, false, false); greyscaleBackground(); + locationButton.setLocationLoad(UNKNOWN); + locationButton.showBridgeIndicator(false); + locationButton.setText(getString(R.string.gateway_selection_title)); + locationButton.showRecommendedIndicator(false); + mainDescription.setText(R.string.eip_state_insecure); + subDescription.setText(R.string.connection_not_connected); } } @@ -461,7 +489,7 @@ public class EipFragment extends Fragment implements Observer { View layout = inflater.inflate(R.layout.custom_toast, activity.findViewById(R.id.custom_toast_container)); - TextView text = layout.findViewById(R.id.text); + AppCompatTextView text = layout.findViewById(R.id.text); text.setText(message); Vibrator v = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); @@ -485,20 +513,8 @@ public class EipFragment extends Fragment implements Observer { showToast(activity, message, true ); } - private void showConnectingLayout(Context activity) { - showConnectionTransitionLayout(activity, true); - } - - private void showDisconnectingLayout(Activity activity) { - showConnectionTransitionLayout(activity, false); - } - - private void showConnectionTransitionLayout(Context activity, boolean isConnecting) { - mainButton.setText(activity.getString(android.R.string.cancel)); - vpnStateImage.setStateIcon(R.drawable.vpn_connecting); - vpnStateImage.showProgress(); - routedText.setVisibility(GONE); - vpnRoute.setVisibility(GONE); + private void showConnectionTransitionLayout(boolean isConnecting) { + mainButton.updateState(true, true, false); if (isConnecting) { colorBackgroundALittle(); } else { @@ -533,21 +549,27 @@ public class EipFragment extends Fragment implements Observer { } private void greyscaleBackground() { - ColorMatrix matrix = new ColorMatrix(); - matrix.setSaturation(0); - ColorMatrixColorFilter cf = new ColorMatrixColorFilter(matrix); - background.setColorFilter(cf); - background.setImageAlpha(255); + if (BuildConfig.use_color_filter) { + ColorMatrix matrix = new ColorMatrix(); + matrix.setSaturation(0); + ColorMatrixColorFilter cf = new ColorMatrixColorFilter(matrix); + background.setColorFilter(cf); + background.setImageAlpha(255); + } } private void colorBackgroundALittle() { - background.setColorFilter(null); - background.setImageAlpha(144); + if (BuildConfig.use_color_filter) { + background.setColorFilter(null); + background.setImageAlpha(144); + } } private void colorBackground() { - background.setColorFilter(null); - background.setImageAlpha(210); + if (BuildConfig.use_color_filter) { + background.setColorFilter(null); + background.setImageAlpha(210); + } } private void updateInvalidVpnCertificate() { @@ -568,15 +590,6 @@ public class EipFragment extends Fragment implements Observer { } } - private void setVpnRouteText() { - String vpnRouteString = provider.getName(); - String profileName = VpnStatus.getLastConnectedVpnName(); - if (!TextUtils.isEmpty(profileName)) { - vpnRouteString += " (" + profileName + ")"; - } - vpnRoute.setText(vpnRouteString); - } - private class EipFragmentServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName className, diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/ExcludeAppsFragment.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/ExcludeAppsFragment.java index 18000171..04745d42 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/ExcludeAppsFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/ExcludeAppsFragment.java @@ -11,7 +11,6 @@ import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; @@ -27,7 +26,9 @@ import android.widget.Filterable; import android.widget.ImageView; import android.widget.ListView; import android.widget.SearchView; -import android.widget.TextView; + +import androidx.appcompat.widget.AppCompatTextView; +import androidx.fragment.app.Fragment; import java.util.Collections; import java.util.List; @@ -38,11 +39,12 @@ import java.util.Vector; import de.blinkt.openvpn.VpnProfile; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.base.utils.PreferenceHelper; +import se.leap.bitmaskclient.base.views.SimpleCheckBox; /** * Created by arne on 16.11.14. */ -public class ExcludeAppsFragment extends Fragment implements AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener { +public class ExcludeAppsFragment extends Fragment implements AdapterView.OnItemClickListener, SimpleCheckBox.OnCheckedChangeListener, View.OnClickListener { private ListView mListView; private VpnProfile mProfile; private PackageAdapter mListAdapter; @@ -77,11 +79,11 @@ public class ExcludeAppsFragment extends Fragment implements AdapterView.OnItemC static class AppViewHolder { public ApplicationInfo mInfo; public View rootView; - public TextView appName; + public AppCompatTextView appName; public ImageView appIcon; - //public TextView appSize; - //public TextView disabled; - public CompoundButton checkBox; + //public AppCompatTextView appSize; + //public AppCompatTextView disabled; + public SimpleCheckBox checkBox; static public AppViewHolder createOrRecycle(LayoutInflater inflater, View convertView, ViewGroup parent) { if (convertView == null) { @@ -107,7 +109,7 @@ public class ExcludeAppsFragment extends Fragment implements AdapterView.OnItemC } @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + public void onCheckedChanged(SimpleCheckBox buttonView, boolean isChecked) { String packageName = (String) buttonView.getTag(); if (isChecked) { diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/GatewaySelectionFragment.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/GatewaySelectionFragment.java index d1222cd7..e3845164 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/GatewaySelectionFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/GatewaySelectionFragment.java @@ -17,9 +17,9 @@ package se.leap.bitmaskclient.base.fragments; import android.app.Activity; +import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; @@ -28,50 +28,53 @@ import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatButton; -import androidx.appcompat.widget.AppCompatImageView; -import androidx.appcompat.widget.AppCompatTextView; -import androidx.core.content.ContextCompat; -import androidx.core.graphics.drawable.DrawableCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; +import java.lang.ref.WeakReference; import java.util.List; import java.util.Observable; import java.util.Observer; +import de.blinkt.openvpn.core.VpnStatus; +import de.blinkt.openvpn.core.connection.Connection; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.base.MainActivity; import se.leap.bitmaskclient.base.models.Location; import se.leap.bitmaskclient.base.utils.PreferenceHelper; -import se.leap.bitmaskclient.base.views.IconSwitchEntry; +import se.leap.bitmaskclient.base.views.SelectLocationEntry; +import se.leap.bitmaskclient.eip.EIP; import se.leap.bitmaskclient.eip.EipCommand; import se.leap.bitmaskclient.eip.EipStatus; import se.leap.bitmaskclient.eip.GatewaysManager; import static android.content.Context.MODE_PRIVATE; -import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; +import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4; +import static de.blinkt.openvpn.core.connection.Connection.TransportType.OPENVPN; +import static se.leap.bitmaskclient.base.MainActivity.ACTION_SHOW_DIALOG_FRAGMENT; import static se.leap.bitmaskclient.base.MainActivity.ACTION_SHOW_VPN_FRAGMENT; -import static se.leap.bitmaskclient.base.models.Constants.PREFERRED_CITY; +import static se.leap.bitmaskclient.base.models.Constants.LOCATION; import static se.leap.bitmaskclient.base.models.Constants.SHARED_PREFERENCES; import static se.leap.bitmaskclient.base.models.Constants.USE_BRIDGES; -import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getPreferredCity; -import static se.leap.bitmaskclient.base.utils.PreferenceHelper.setPreferredCity; -public class GatewaySelectionFragment extends Fragment implements SharedPreferences.OnSharedPreferenceChangeListener, Observer { +interface LocationListSelectionListener { + void onLocationManuallySelected(Location location); +} + +public class GatewaySelectionFragment extends Fragment implements Observer, LocationListSelectionListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = GatewaySelectionFragment.class.getSimpleName(); private RecyclerView recyclerView; private LocationListAdapter locationListAdapter; - private IconSwitchEntry autoSelectionSwitch; - private AppCompatButton vpnButton; + private SelectLocationEntry recommendedLocation; private GatewaysManager gatewaysManager; - private SharedPreferences preferences; private EipStatus eipStatus; + private SharedPreferences preferences; + private Connection.TransportType selectedTransport; public GatewaySelectionFragment() { // Required empty public constructor @@ -81,8 +84,11 @@ public class GatewaySelectionFragment extends Fragment implements SharedPreferen public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gatewaysManager = new GatewaysManager(getContext()); - preferences = getContext().getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); eipStatus = EipStatus.getInstance(); + eipStatus.addObserver(this); + preferences = getContext().getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); + selectedTransport = PreferenceHelper.getUseBridges(preferences) ? OBFS4 : OPENVPN; + preferences.registerOnSharedPreferenceChangeListener(this); } @Override @@ -96,78 +102,90 @@ public class GatewaySelectionFragment extends Fragment implements SharedPreferen public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initRecyclerView(); - initAutoSelectionSwitch(); - initVpnButton(); - eipStatus.addObserver(this); - preferences.registerOnSharedPreferenceChangeListener(this); + initRecommendedLocationEntry(); } @Override public void onDestroyView() { super.onDestroyView(); - preferences.unregisterOnSharedPreferenceChangeListener(this); eipStatus.deleteObserver(this); + preferences.unregisterOnSharedPreferenceChangeListener(this); } - - private void initRecyclerView() { - recyclerView = (RecyclerView) getActivity().findViewById(R.id.gatewaySelection_list); + recyclerView = getActivity().findViewById(R.id.gatewaySelection_list); recyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); recyclerView.setLayoutManager(layoutManager); - locationListAdapter = new LocationListAdapter(gatewaysManager.getGatewayLocations()); + locationListAdapter = new LocationListAdapter(gatewaysManager.getSortedGatewayLocations(selectedTransport), this, selectedTransport); recyclerView.setAdapter(locationListAdapter); - recyclerView.setVisibility(getPreferredCity(getContext()) == null ? INVISIBLE : VISIBLE); + recyclerView.setVisibility(VISIBLE); } - private void initAutoSelectionSwitch() { - autoSelectionSwitch = getActivity().findViewById(R.id.automatic_gateway_switch); - autoSelectionSwitch.setSingleLine(false); - autoSelectionSwitch.setSubtitle(getString(R.string.gateway_selection_warning, getString(R.string.app_name))); - autoSelectionSwitch.setChecked(getPreferredCity(getContext()) == null); - autoSelectionSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { - recyclerView.setVisibility(!isChecked ? VISIBLE : View.GONE); - Log.d(TAG, "autoselection enabled: " + isChecked); - if (isChecked) { - PreferenceHelper.setPreferredCity(getContext(), null); - locationListAdapter.resetSelection(); - } - setVpnButtonState(); + private void initRecommendedLocationEntry() { + recommendedLocation = getActivity().findViewById(R.id.recommended_location); + recommendedLocation.setTitle(getString(R.string.gateway_selection_automatic_location)); + recommendedLocation.showDivider(true); + recommendedLocation.setOnClickListener(v -> { + recommendedLocation.setSelected(true); + locationListAdapter.unselectAll(); + startEipService(null); }); + updateRecommendedLocation(); + } + + private void updateRecommendedLocation() { + Location location = new Location(); + boolean isManualSelection = PreferenceHelper.getPreferredCity(getContext()) != null; + if (!isManualSelection && eipStatus.isConnected()) { + try { + location = gatewaysManager.getLocation(VpnStatus.getCurrentlyConnectingVpnName()).clone(); + } catch (NullPointerException | CloneNotSupportedException e) { + e.printStackTrace(); + } + } + location.selected = !isManualSelection; + if (!isManualSelection) { + locationListAdapter.unselectAll(); + } + recommendedLocation.setLocation(location, selectedTransport); } - private void initVpnButton() { - vpnButton = getActivity().findViewById(R.id.vpn_button); - setVpnButtonState(); - vpnButton.setOnClickListener(v -> { - EipCommand.startVPN(getContext(), false); + protected void startEipService(String preferredCity) { + new Thread(() -> { + Context context = getContext(); + if (context == null) { + return; + } + PreferenceHelper.setPreferredCity(context, preferredCity); + EipCommand.startVPN(context, false); Intent intent = new Intent(getContext(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setAction(ACTION_SHOW_VPN_FRAGMENT); startActivity(intent); - }); + }).start(); } - private void setVpnButtonState() { - if (eipStatus.isDisconnected()) { - vpnButton.setText(R.string.vpn_button_turn_on); + @Override + public void onLocationManuallySelected(Location location) { + recommendedLocation.setSelected(false); + String name = location.getName(); + if (location.supportsTransport(selectedTransport)) { + startEipService(name); } else { - vpnButton.setText(R.string.reconnect); + locationListAdapter.unselectAll(); + askToChangeTransport(name); } - vpnButton.setEnabled( - (locationListAdapter.selectedLocation != null && locationListAdapter.selectedLocation.selected) || - autoSelectionSwitch.isChecked()); } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (USE_BRIDGES.equals(key)) { - locationListAdapter.updateData(gatewaysManager.getGatewayLocations()); - setVpnButtonState(); - } else if (PREFERRED_CITY.equals(key)) { - setVpnButtonState(); - } + private void askToChangeTransport(String name) { + Intent intent = new Intent(getContext(), MainActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); + intent.setAction(ACTION_SHOW_DIALOG_FRAGMENT); + intent.putExtra(EIP.ERRORID, EIP.EIPErrors.TRANSPORT_NOT_SUPPORTED.toString()); + intent.putExtra(EIP.ERRORS, getString(R.string.warning_bridges_not_supported, name)); + intent.putExtra(LOCATION, name); + startActivity(intent); } @Override @@ -176,29 +194,32 @@ public class GatewaySelectionFragment extends Fragment implements SharedPreferen eipStatus = (EipStatus) o; Activity activity = getActivity(); if (activity != null) { - activity.runOnUiThread(this::setVpnButtonState); + activity.runOnUiThread(this::updateRecommendedLocation); } } + } + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + if (key.equals(USE_BRIDGES)) { + selectedTransport = PreferenceHelper.getUseBridges(sharedPreferences) ? OBFS4 : OPENVPN; + gatewaysManager.updateTransport(selectedTransport); + locationListAdapter.updateTransport(selectedTransport, gatewaysManager); + } } static class LocationListAdapter extends RecyclerView.Adapter<LocationListAdapter.ViewHolder> { private static final String TAG = LocationListAdapter.class.getSimpleName(); + private Connection.TransportType transport; private List<Location> values; - private Location selectedLocation = null; + private final WeakReference<LocationListSelectionListener> callback; static class ViewHolder extends RecyclerView.ViewHolder { - public AppCompatTextView locationLabel; - public AppCompatTextView qualityLabel; - public AppCompatImageView checkedIcon; - public View layout; + public SelectLocationEntry entry; - public ViewHolder(View v) { + public ViewHolder(SelectLocationEntry v) { super(v); - layout = v; - locationLabel = (AppCompatTextView) v.findViewById(R.id.location); - qualityLabel = (AppCompatTextView) v.findViewById(R.id.quality); - checkedIcon = (AppCompatImageView) v.findViewById(R.id.checked_icon); + entry = v; } } @@ -212,78 +233,50 @@ public class GatewaySelectionFragment extends Fragment implements SharedPreferen notifyItemRemoved(position); } - public void resetSelection() { - if (selectedLocation != null) { - selectedLocation.selected = false; - notifyDataSetChanged(); - } + public void updateTransport(Connection.TransportType transportType, GatewaysManager gatewaysManager) { + transport = transportType; + values = gatewaysManager.getSortedGatewayLocations(transportType); + notifyDataSetChanged(); } - public void updateData(List<Location> data) { - values = data; + public void unselectAll() { + for (Location l : values) { + l.selected = false; + } notifyDataSetChanged(); } - public LocationListAdapter(List<Location> data) { + public LocationListAdapter(List<Location> data, LocationListSelectionListener selectionListener, Connection.TransportType selectedTransport) { values = data; + callback = new WeakReference<>(selectionListener); + transport = selectedTransport; } @NonNull @Override public LocationListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - LayoutInflater inflater = LayoutInflater.from( - parent.getContext()); - View v = inflater.inflate(R.layout.v_select_text_list_item, parent, false); - return new ViewHolder(v); + SelectLocationEntry entry = new SelectLocationEntry(parent.getContext()); + return new ViewHolder(entry); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, final int position) { final Location location = values.get(position); - holder.locationLabel.setText(location.name); - holder.layout.setOnClickListener(v -> { - Log.d(TAG, "view at position clicked: " + position); - if (selectedLocation == null) { - selectedLocation = location; - selectedLocation.selected = true; - } else if (selectedLocation.name.equals(location.name)){ - selectedLocation.selected = !selectedLocation.selected; - } else { - selectedLocation.selected = false; - selectedLocation = location; - selectedLocation.selected = true; + holder.entry.setLocation(location, transport); + holder.entry.setOnClickListener(v -> { + Log.d(TAG, "onClick view at position clicked: " + position); + LocationListSelectionListener listener = callback.get(); + if (listener != null) { + unselectAll(); + location.selected = true; + listener.onLocationManuallySelected(location); + notifyDataSetChanged(); } - setPreferredCity(holder.layout.getContext(), selectedLocation.selected ? selectedLocation.name : null); - holder.checkedIcon.setVisibility(selectedLocation.selected ? VISIBLE : INVISIBLE); - notifyDataSetChanged(); }); - Drawable checkIcon = DrawableCompat.wrap(holder.layout.getContext().getResources().getDrawable(R.drawable.ic_check_bold)).mutate(); - DrawableCompat.setTint(checkIcon, ContextCompat.getColor(holder.layout.getContext(), R.color.colorSuccess)); - holder.checkedIcon.setImageDrawable(checkIcon); - holder.checkedIcon.setVisibility(location.selected ? VISIBLE : INVISIBLE); - holder.qualityLabel.setText(getQualityString(location.averageLoad)); - if (location.selected) { - selectedLocation = location; - } } - public String getQualityString(double quality) { - if (quality == 0) { - return ""; - } else if (quality < 0.25) { - return "BAD"; - } else if (quality < 0.6) { - return "AVERAGE"; - } else if (quality < 0.8){ - return "GOOD"; - } else { - return "EXCELLENT"; - } - } - - @Override public int getItemCount() { return values.size(); diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/LogFragment.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/LogFragment.java index d788b9e6..a5a5e555 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/LogFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/LogFragment.java @@ -19,8 +19,6 @@ import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.preference.PreferenceManager; -import androidx.annotation.Nullable; -import androidx.fragment.app.ListFragment; import android.text.SpannableString; import android.text.format.DateFormat; import android.view.LayoutInflater; @@ -37,9 +35,12 @@ 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 androidx.annotation.Nullable; +import androidx.appcompat.widget.AppCompatTextView; +import androidx.fragment.app.ListFragment; + import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; @@ -55,8 +56,8 @@ import de.blinkt.openvpn.core.Preferences; import de.blinkt.openvpn.core.VpnStatus; import de.blinkt.openvpn.core.VpnStatus.LogListener; import de.blinkt.openvpn.core.VpnStatus.StateListener; -import se.leap.bitmaskclient.base.models.Constants; import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.base.models.Constants; import static de.blinkt.openvpn.core.OpenVPNService.humanReadableByteCount; @@ -70,9 +71,9 @@ public class LogFragment extends ListFragment implements StateListener, SeekBar. private SeekBar mLogLevelSlider; private LinearLayout mOptionsLayout; private RadioGroup mTimeRadioGroup; - private TextView mUpStatus; - private TextView mDownStatus; - private TextView mConnectStatus; + private AppCompatTextView mUpStatus; + private AppCompatTextView mDownStatus; + private AppCompatTextView mConnectStatus; private boolean mShowOptionsLayout; private CheckBox mClearLogCheckBox; @@ -219,11 +220,11 @@ public class LogFragment extends ListFragment implements StateListener, SeekBar. @Override public View getView(int position, View convertView, ViewGroup parent) { - TextView v; + AppCompatTextView v; if (convertView == null) - v = new TextView(getActivity()); + v = new AppCompatTextView(getActivity()); else - v = (TextView) convertView; + v = (AppCompatTextView) convertView; LogItem le = currentLevelEntries.get(position); String msg = le.getString(getActivity()); @@ -380,7 +381,7 @@ public class LogFragment extends ListFragment implements StateListener, SeekBar. private LogWindowListAdapter ladapter; - private TextView mSpeedView; + private AppCompatTextView mSpeedView; @Override @@ -474,7 +475,7 @@ public class LogFragment extends ListFragment implements StateListener, SeekBar. int position, long id) { ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("Log Entry", ((TextView) view).getText()); + ClipData clip = ClipData.newPlainText("Log Entry", ((AppCompatTextView) view).getText()); clipboard.setPrimaryClip(clip); Toast.makeText(getActivity(), R.string.copied_entry, Toast.LENGTH_SHORT).show(); return true; diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/MainActivityErrorDialog.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/MainActivityErrorDialog.java index 86f8471c..f7805002 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/MainActivityErrorDialog.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/MainActivityErrorDialog.java @@ -18,6 +18,8 @@ package se.leap.bitmaskclient.base.fragments; import android.app.Dialog; import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -27,11 +29,15 @@ import androidx.appcompat.app.AlertDialog; import org.json.JSONObject; import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.base.MainActivity; +import se.leap.bitmaskclient.base.utils.PreferenceHelper; import se.leap.bitmaskclient.eip.EIP; import se.leap.bitmaskclient.eip.EipCommand; import se.leap.bitmaskclient.base.models.Provider; import se.leap.bitmaskclient.providersetup.ProviderAPICommand; +import static se.leap.bitmaskclient.base.MainActivity.ACTION_SHOW_DIALOG_FRAGMENT; +import static se.leap.bitmaskclient.base.MainActivity.ACTION_SHOW_VPN_FRAGMENT; import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getPreferredCity; import static se.leap.bitmaskclient.base.utils.PreferenceHelper.setPreferredCity; import static se.leap.bitmaskclient.providersetup.ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE; @@ -56,6 +62,7 @@ public class MainActivityErrorDialog extends DialogFragment { final private static String KEY_REASON_TO_FAIL = "key reason to fail"; final private static String KEY_PROVIDER = "key provider"; private String reasonToFail; + private String[] args; private EIP.EIPErrors downloadError = UNKNOWN; private Provider provider; @@ -70,11 +77,12 @@ public class MainActivityErrorDialog extends DialogFragment { /** * @return a new instance of this DialogFragment. */ - public static DialogFragment newInstance(Provider provider, String reasonToFail, EIP.EIPErrors error) { + public static DialogFragment newInstance(Provider provider, String reasonToFail, EIP.EIPErrors error, String... args) { MainActivityErrorDialog dialogFragment = new MainActivityErrorDialog(); dialogFragment.reasonToFail = reasonToFail; dialogFragment.provider = provider; dialogFragment.downloadError = error; + dialogFragment.args = args; return dialogFragment; } @@ -124,8 +132,10 @@ public class MainActivityErrorDialog extends DialogFragment { builder.setNegativeButton(R.string.cancel, (dialog, id) -> {}); if (getPreferredCity(applicationContext) != null) { builder.setPositiveButton(R.string.warning_option_try_best, (dialog, which) -> { - setPreferredCity(applicationContext, null); - EipCommand.startVPN(applicationContext, false); + new Thread(() -> { + setPreferredCity(applicationContext, null); + EipCommand.startVPN(applicationContext, false); + }).start(); }); } else if (provider.supportsPluggableTransports()) { if (getUseBridges(applicationContext)) { @@ -148,6 +158,21 @@ public class MainActivityErrorDialog extends DialogFragment { case ERROR_VPN_PREPARE: builder.setPositiveButton(android.R.string.ok, (dialog, which) -> { }); break; + case TRANSPORT_NOT_SUPPORTED: + + builder.setPositiveButton(R.string.option_different_location, (dialog, which) -> { }); + builder.setNegativeButton(R.string.option_disable_bridges, (dialog, which) -> { + PreferenceHelper.useBridges(applicationContext, false); + PreferenceHelper.setPreferredCity(applicationContext, args[0]); + + EipCommand.startVPN(applicationContext, false); + // at this point the gateway selection dialog is shown, let's switch to the main view + Intent intent = new Intent(getContext(), MainActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); + intent.setAction(ACTION_SHOW_VPN_FRAGMENT); + startActivity(intent); + }); + break; default: break; } diff --git a/app/src/main/java/se/leap/bitmaskclient/base/fragments/NavigationDrawerFragment.java b/app/src/main/java/se/leap/bitmaskclient/base/fragments/NavigationDrawerFragment.java index a13692a5..020a48a4 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/fragments/NavigationDrawerFragment.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/fragments/NavigationDrawerFragment.java @@ -27,6 +27,7 @@ import android.os.Bundle; import android.os.Handler; import androidx.annotation.NonNull; import androidx.annotation.StringRes; +import androidx.appcompat.widget.AppCompatTextView; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; @@ -380,7 +381,7 @@ public class NavigationDrawerFragment extends Fragment implements SharedPreferen } private void initShowExperimentalHint() { - TextView textView = drawerLayout.findViewById(R.id.show_experimental_features); + AppCompatTextView textView = drawerLayout.findViewById(R.id.show_experimental_features); textView.setText(showExperimentalFeatures(getContext()) ? R.string.hide_experimental : R.string.show_experimental); textView.setOnClickListener(v -> { boolean shown = showExperimentalFeatures(getContext()); @@ -388,12 +389,12 @@ public class NavigationDrawerFragment extends Fragment implements SharedPreferen tethering.setVisibility(GONE); firewall.setVisibility(GONE); experimentalFeatureFooter.setVisibility(GONE); - ((TextView) v).setText(R.string.show_experimental); + ((AppCompatTextView) v).setText(R.string.show_experimental); } else { tethering.setVisibility(VISIBLE); firewall.setVisibility(VISIBLE); experimentalFeatureFooter.setVisibility(VISIBLE); - ((TextView) v).setText(R.string.hide_experimental); + ((AppCompatTextView) v).setText(R.string.hide_experimental); } PreferenceHelper.setShowExperimentalFeatures(getContext(), !shown); }); @@ -425,7 +426,7 @@ public class NavigationDrawerFragment extends Fragment implements SharedPreferen } manualGatewaySelection = drawerView.findViewById(R.id.manualGatewaySelection); String preferredGateway = getPreferredCity(getContext()); - String subtitle = preferredGateway != null ? preferredGateway : getString(R.string.gateway_selection_best_location); + String subtitle = preferredGateway != null ? preferredGateway : getString(R.string.gateway_selection_recommended_location); manualGatewaySelection.setSubtitle(subtitle); boolean show = ProviderObservable.getInstance().getCurrentProvider().hasGatewaysInDifferentLocations(); manualGatewaySelection.setVisibility(show ? VISIBLE : GONE); diff --git a/app/src/main/java/se/leap/bitmaskclient/base/models/Location.java b/app/src/main/java/se/leap/bitmaskclient/base/models/Location.java index ae7818ba..064f25c0 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/models/Location.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/models/Location.java @@ -1,20 +1,85 @@ +/** + * Copyright (c) 2021 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 <http://www.gnu.org/licenses/>. + */ + package se.leap.bitmaskclient.base.models; import androidx.annotation.NonNull; -public class Location { - @NonNull public String name; - public double averageLoad; - public int numberOfGateways; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.function.ToDoubleFunction; + +import de.blinkt.openvpn.core.connection.Connection; +import de.blinkt.openvpn.core.connection.Connection.TransportType; + +public class Location implements Cloneable { + @NonNull private String name = ""; + @NonNull private HashMap<TransportType, Double> averageLoad = new HashMap<>(); + @NonNull private HashMap<TransportType, Integer> numberOfGateways = new HashMap<>(); public boolean selected; - public Location(@NonNull String name, double averageLoad, int numberOfGateways, boolean selected) { + public Location() {} + + public Location(@NonNull String name, + @NonNull HashMap<TransportType, Double> averageLoad, + @NonNull HashMap<TransportType, Integer> numberOfGateways, + boolean selected) { this.name = name; this.averageLoad = averageLoad; this.numberOfGateways = numberOfGateways; this.selected = selected; } + public boolean hasLocationInfo() { + return !numberOfGateways.isEmpty() && !averageLoad.isEmpty() && !name.isEmpty(); + } + + public boolean supportsTransport(TransportType transportType) { + return numberOfGateways.containsKey(transportType); + } + + public void setAverageLoad(TransportType transportType, double load) { + averageLoad.put(transportType, load); + } + + public double getAverageLoad(TransportType transportType) { + if (averageLoad.containsKey(transportType)) { + return averageLoad.get(transportType); + } + return 0; + } + + public void setNumberOfGateways(TransportType transportType, int numbers) { + numberOfGateways.put(transportType, numbers); + } + + public int getNumberOfGateways(TransportType transportType) { + if (numberOfGateways.containsKey(transportType)) { + return numberOfGateways.get(transportType); + } + return 0; + } + + @NonNull + public String getName() { + return name; + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -22,21 +87,43 @@ public class Location { Location location = (Location) o; - if (Double.compare(location.averageLoad, averageLoad) != 0) return false; - if (numberOfGateways != location.numberOfGateways) return false; - if (selected != location.selected) return false; - return name.equals(location.name); + if (!name.equals(location.name)) return false; + if (!averageLoad.equals(location.averageLoad)) return false; + return numberOfGateways.equals(location.numberOfGateways); } @Override public int hashCode() { - int result; - long temp; - result = name.hashCode(); - temp = Double.doubleToLongBits(averageLoad); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - result = 31 * result + numberOfGateways; - result = 31 * result + (selected ? 1 : 0); + int result = name.hashCode(); + result = 31 * result + averageLoad.hashCode(); + result = 31 * result + numberOfGateways.hashCode(); return result; } + + @Override + public Location clone() throws CloneNotSupportedException { + Location copy = (Location) super.clone(); + copy.name = this.name; + copy.numberOfGateways = (HashMap<TransportType, Integer>) this.numberOfGateways.clone(); + copy.averageLoad = (HashMap<TransportType, Double>) this.averageLoad.clone(); + return copy; + } + + public static class SortByAverageLoad implements Comparator<Location> { + TransportType transportType; + public SortByAverageLoad(TransportType transportType) { + this.transportType = transportType; + } + + @Override + public int compare(Location location1, Location location2) { + if (location1.supportsTransport(transportType) && location2.supportsTransport(transportType)) { + return (int) (location1.getAverageLoad(transportType) * 100) - (int) (location2.getAverageLoad(transportType) * 100); + } else if (location1.supportsTransport(transportType) && !location2.supportsTransport(transportType)) { + return -1; + } else { + return 1; + } + } + } } diff --git a/app/src/main/java/se/leap/bitmaskclient/base/utils/ConfigHelper.java b/app/src/main/java/se/leap/bitmaskclient/base/utils/ConfigHelper.java index 64b51960..6c242e5a 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/utils/ConfigHelper.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/utils/ConfigHelper.java @@ -197,6 +197,26 @@ public class ConfigHelper { return Calendar.getInstance().get(Calendar.ZONE_OFFSET) / 3600000; } + public static int timezoneDistance(int local_timezone, int remoteTimezone) { + // Distance along the numberline of Prime Meridian centric, assumes UTC-11 through UTC+12 + int dist = Math.abs(local_timezone - remoteTimezone); + // Farther than 12 timezones and it's shorter around the "back" + if (dist > 12) + dist = 12 - (dist - 12); // Well i'll be. Absolute values make equations do funny things. + return dist; + } + + /** + * + * @param remoteTimezone + * @return a value between 0.1 and 1.0 + */ + public static double getConnectionQualityFromTimezoneDistance(int remoteTimezone) { + int localTimeZone = ConfigHelper.getCurrentTimezone(); + int distance = ConfigHelper.timezoneDistance(localTimeZone, remoteTimezone); + return Math.max(distance / 12.0, 0.1); + } + public static String getProviderFormattedString(Resources resources, @StringRes int resourceId) { String appName = resources.getString(R.string.app_name); return resources.getString(resourceId, appName); diff --git a/app/src/main/java/se/leap/bitmaskclient/base/utils/PreferenceHelper.java b/app/src/main/java/se/leap/bitmaskclient/base/utils/PreferenceHelper.java index 06fb25e9..40b7fc05 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/utils/PreferenceHelper.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/utils/PreferenceHelper.java @@ -2,7 +2,9 @@ package se.leap.bitmaskclient.base.utils; import android.content.Context; import android.content.SharedPreferences; + import androidx.annotation.NonNull; +import androidx.annotation.WorkerThread; import org.json.JSONException; import org.json.JSONObject; @@ -33,8 +35,8 @@ import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_VPN_CERTIFICA import static se.leap.bitmaskclient.base.models.Constants.RESTART_ON_UPDATE; import static se.leap.bitmaskclient.base.models.Constants.SHARED_PREFERENCES; import static se.leap.bitmaskclient.base.models.Constants.SHOW_EXPERIMENTAL; -import static se.leap.bitmaskclient.base.models.Constants.USE_IPv6_FIREWALL; import static se.leap.bitmaskclient.base.models.Constants.USE_BRIDGES; +import static se.leap.bitmaskclient.base.models.Constants.USE_IPv6_FIREWALL; import static se.leap.bitmaskclient.base.models.Constants.USE_TOR; /** @@ -229,8 +231,9 @@ public class PreferenceHelper { return getString(context, PREFERRED_CITY, null); } + @WorkerThread public static void setPreferredCity(Context context, String city) { - putString(context, PREFERRED_CITY, city); + putStringSync(context, PREFERRED_CITY, city); } public static JSONObject getEipDefinitionFromPreferences(SharedPreferences preferences) { @@ -263,21 +266,42 @@ public class PreferenceHelper { } public static long getLong(Context context, String key, long defValue) { + if (context == null) { + return defValue; + } SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); return preferences.getLong(key, defValue); } public static void putLong(Context context, String key, long value) { + if (context == null) { + return; + } SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); preferences.edit().putLong(key, value).apply(); } public static String getString(Context context, String key, String defValue) { + if (context == null) { + return defValue; + } SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); return preferences.getString(key, defValue); } + @WorkerThread + public static void putStringSync(Context context, String key, String value) { + if (context == null) { + return; + } + SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); + preferences.edit().putString(key, value).commit(); + } + public static void putString(Context context, String key, String value) { + if (context == null) { + return; + } SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); preferences.edit().putString(key, value).apply(); } diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/IconCheckboxEntry.java b/app/src/main/java/se/leap/bitmaskclient/base/views/IconCheckboxEntry.java index 977056f7..0957712b 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/views/IconCheckboxEntry.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/IconCheckboxEntry.java @@ -7,10 +7,10 @@ import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; -import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageView; +import androidx.appcompat.widget.AppCompatTextView; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.DrawableCompat; @@ -23,7 +23,7 @@ import se.leap.bitmaskclient.base.fragments.TetheringDialog; public class IconCheckboxEntry extends LinearLayout { @BindView(android.R.id.text1) - TextView textView; + AppCompatTextView textView; @BindView(R.id.material_icon) AppCompatImageView iconView; diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/IconSwitchEntry.java b/app/src/main/java/se/leap/bitmaskclient/base/views/IconSwitchEntry.java index b6d72ab6..a499cdd1 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/views/IconSwitchEntry.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/IconSwitchEntry.java @@ -24,6 +24,7 @@ import androidx.annotation.DrawableRes; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.widget.AppCompatImageView; +import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.SwitchCompat; import android.util.AttributeSet; import android.view.LayoutInflater; @@ -36,8 +37,8 @@ import se.leap.bitmaskclient.R; public class IconSwitchEntry extends LinearLayout { - private TextView textView; - private TextView subtitleView; + private AppCompatTextView textView; + private AppCompatTextView subtitleView; private AppCompatImageView iconView; private SwitchCompat switchView; private CompoundButton.OnCheckedChangeListener checkedChangeListener; diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/IconTextEntry.java b/app/src/main/java/se/leap/bitmaskclient/base/views/IconTextEntry.java index 6b9bd760..2d9525ed 100644 --- a/app/src/main/java/se/leap/bitmaskclient/base/views/IconTextEntry.java +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/IconTextEntry.java @@ -4,25 +4,26 @@ import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; -import androidx.annotation.ColorRes; -import androidx.annotation.DrawableRes; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; -import android.widget.TextView; + +import androidx.annotation.ColorRes; +import androidx.annotation.DrawableRes; +import androidx.annotation.Nullable; +import androidx.annotation.StringRes; +import androidx.appcompat.widget.AppCompatTextView; import se.leap.bitmaskclient.R; public class IconTextEntry extends LinearLayout { - private TextView textView; + private AppCompatTextView textView; private ImageView iconView; - private TextView subtitleView; + private AppCompatTextView subtitleView; public IconTextEntry(Context context) { super(context); diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/LocationButton.java b/app/src/main/java/se/leap/bitmaskclient/base/views/LocationButton.java new file mode 100644 index 00000000..b2182d61 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/LocationButton.java @@ -0,0 +1,58 @@ +package se.leap.bitmaskclient.base.views; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.RelativeLayout; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.widget.AppCompatImageView; +import androidx.appcompat.widget.AppCompatTextView; + +import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.eip.GatewaysManager; + +public class LocationButton extends RelativeLayout { + private LocationIndicator locationIndicator; + private AppCompatTextView textView; + private AppCompatImageView bridgeView; + private AppCompatImageView recommendedView; + + public LocationButton(@NonNull Context context) { + super(context); + initLayout(context); + } + + public LocationButton(@NonNull Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + initLayout(context); + } + + private void initLayout(Context context) { + LayoutInflater inflater = (LayoutInflater) context + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View rootview = inflater.inflate(R.layout.v_location_button, this, true); + locationIndicator = rootview.findViewById(R.id.load_indicator); + textView = rootview.findViewById(R.id.text_location); + bridgeView = rootview.findViewById(R.id.bridge_icn); + recommendedView = rootview.findViewById(R.id.recommended_icn); + } + + public void setLocationLoad(GatewaysManager.Load load) { + locationIndicator.setLoad(load); + } + + public void setText(CharSequence text) { + textView.setText(text); + } + + public void showBridgeIndicator(boolean show) { + bridgeView.setVisibility(show ? VISIBLE : GONE); + } + + public void showRecommendedIndicator(boolean show) { + recommendedView.setVisibility(show? VISIBLE : GONE ); + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/LocationIndicator.java b/app/src/main/java/se/leap/bitmaskclient/base/views/LocationIndicator.java new file mode 100644 index 00000000..8245893d --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/LocationIndicator.java @@ -0,0 +1,91 @@ +package se.leap.bitmaskclient.base.views; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.LinearLayout; + +import androidx.annotation.Nullable; +import androidx.core.content.ContextCompat; + +import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.eip.GatewaysManager; + +import static androidx.core.content.ContextCompat.getColor; + +public class LocationIndicator extends LinearLayout { + + private View level1; + private View level1_2; + private View level2; + private View level2_2; + private View level3; + private View level3_2; + + public LocationIndicator(Context context) { + super(context); + initLayout(context); + } + + public LocationIndicator(Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + initLayout(context); + + } + + public LocationIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initLayout(context); + } + + + void initLayout(Context context) { + LayoutInflater inflater = (LayoutInflater) context + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View rootview = inflater.inflate(R.layout.v_location_status_indicator, this, true); + level1 = rootview.findViewById(R.id.level1); + level1_2 = rootview.findViewById(R.id.level1_2); + level2 = rootview.findViewById(R.id.level2); + level2_2 = rootview.findViewById(R.id.level2_2); + level3 = rootview.findViewById(R.id.level3); + level3_2 = rootview.findViewById(R.id.level3_2); + } + + public void setLoad(GatewaysManager.Load load) { + switch (load) { + case GOOD: + level1.setBackgroundColor(getColor(getContext(), R.color.green200)); + level1_2.setBackgroundColor(getColor(getContext(), R.color.green200)); + level2.setBackgroundColor(getColor(getContext(), R.color.green200)); + level2_2.setBackgroundColor(getColor(getContext(), R.color.green200)); + level3.setBackgroundColor(getColor(getContext(), R.color.green200)); + level3_2.setBackgroundColor(getColor(getContext(), R.color.green200)); + break; + case AVERAGE: + level1.setBackgroundColor(getColor(getContext(), R.color.yellow200)); + level1_2.setBackgroundColor(getColor(getContext(), R.color.yellow200)); + level2.setBackgroundColor(getColor(getContext(), R.color.yellow200)); + level2_2.setBackgroundColor(getColor(getContext(), R.color.yellow200)); + level3.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level3_2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + break; + case CRITICAL: + level1.setBackgroundColor(getColor(getContext(), R.color.red200)); + level1_2.setBackgroundColor(getColor(getContext(), R.color.red200)); + level2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level2_2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level3.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level3_2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + break; + default: + level1.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level1_2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level2_2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level3.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent)); + level3_2.setBackgroundColor(getColor(getContext(), R.color.black800_high_transparent));; + break; + } + } +} diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/MainButton.java b/app/src/main/java/se/leap/bitmaskclient/base/views/MainButton.java new file mode 100644 index 00000000..c5ac4544 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/MainButton.java @@ -0,0 +1,124 @@ +package se.leap.bitmaskclient.base.views; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.PorterDuff; +import android.graphics.drawable.AnimationDrawable; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; +import android.widget.RelativeLayout; + +import androidx.annotation.ColorRes; +import androidx.annotation.DrawableRes; +import androidx.appcompat.widget.AppCompatImageView; +import androidx.core.content.ContextCompat; + +import se.leap.bitmaskclient.R; + +public class MainButton extends RelativeLayout { + + private static final String TAG = MainButton.class.getSimpleName(); + + AppCompatImageView glow; + AppCompatImageView shadowLight; + AnimationDrawable glowAnimation; + + private boolean isOn = false; + private boolean isProcessing = false; + private boolean isError = true; + + + public MainButton(Context context) { + super(context); + initLayout(context); + } + + public MainButton(Context context, AttributeSet attrs) { + super(context, attrs); + initLayout(context); + } + + public MainButton(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initLayout(context); + } + + + @TargetApi(21) + public MainButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + initLayout(context); + } + + private void initLayout(Context context) { + LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View rootview = inflater.inflate(R.layout.v_main_btn, this, true); + + glow = rootview.findViewById(R.id.vpn_btn_glow); + glowAnimation = (AnimationDrawable) glow.getBackground(); + shadowLight = rootview.findViewById(R.id.vpn_btn_shadow_light); + } + + + private void stopGlowAnimation() { + AlphaAnimation fadeOutAnimation = new AlphaAnimation(1.0f, 0.0f); + fadeOutAnimation.setDuration(300); + fadeOutAnimation.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) {} + + @Override + public void onAnimationEnd(Animation animation) { + glow.setVisibility(GONE); + glowAnimation.stop(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + glow.startAnimation(fadeOutAnimation); + } + + private void startGlowAnimation() { + glow.setAlpha(1.0f); + glow.setVisibility(VISIBLE); + glowAnimation.start(); + } + + public void updateState(boolean isOn, boolean isProcessing, boolean isError) { + if (this.isOn != isOn) { + this.isOn = isOn; + shadowLight.setVisibility(isOn ? VISIBLE : GONE); + } + + if (this.isProcessing != isProcessing) { + if (!isProcessing) { + stopGlowAnimation(); + } else { + startGlowAnimation(); + } + this.isProcessing = isProcessing; + } + + if (this.isError != isError) { + @DrawableRes int drawableResource = isOn ? R.drawable.on_off_btn_start_2_enabled : R.drawable.on_off_btn_start_2_disabled; + if (!isError) { + setImageWithTint(shadowLight, drawableResource, R.color.colorMainBtnHighlight); + } else { + setImageWithTint(shadowLight, drawableResource, R.color.colorMainBtnError); + } + this.isError = isError; + } + } + + private void setImageWithTint(AppCompatImageView view, @DrawableRes int resourceId, @ColorRes int color) { + view.setImageDrawable(ContextCompat.getDrawable(getContext(), resourceId)); + view.setColorFilter(ContextCompat.getColor(getContext(), color), PorterDuff.Mode.SRC_ATOP); + } + + + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/SelectLocationEntry.java b/app/src/main/java/se/leap/bitmaskclient/base/views/SelectLocationEntry.java new file mode 100644 index 00000000..2a082579 --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/SelectLocationEntry.java @@ -0,0 +1,90 @@ +package se.leap.bitmaskclient.base.views; + +import android.annotation.TargetApi; +import android.content.Context; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; + +import androidx.appcompat.widget.AppCompatImageView; +import androidx.appcompat.widget.AppCompatTextView; + +import de.blinkt.openvpn.core.connection.Connection; +import se.leap.bitmaskclient.R; +import se.leap.bitmaskclient.base.models.Location; +import se.leap.bitmaskclient.eip.GatewaysManager.Load; + +import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4; + +public class SelectLocationEntry extends LinearLayout { + + private static final String TAG = SelectLocationEntry.class.getSimpleName(); + AppCompatTextView title; + AppCompatTextView locationText; + SimpleCheckBox selectedView; + AppCompatImageView bridgesView; + LocationIndicator locationIndicator; + View divider; + + public SelectLocationEntry(Context context) { + super(context); + initLayout(context); + } + + public SelectLocationEntry(Context context, AttributeSet attrs) { + super(context, attrs); + initLayout(context); + } + + public SelectLocationEntry(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initLayout(context); + } + + @TargetApi(21) + public SelectLocationEntry(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + initLayout(context); + } + + private void initLayout(Context context) { + LayoutInflater inflater = (LayoutInflater) context + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View rootview = inflater.inflate(R.layout.v_select_text_list_item, this, true); + title = rootview.findViewById(R.id.title); + locationIndicator = rootview.findViewById(R.id.quality); + locationText = rootview.findViewById(R.id.location); + bridgesView = rootview.findViewById(R.id.bridge_image); + selectedView = rootview.findViewById(R.id.selected); + divider = rootview.findViewById(R.id.divider); + } + + public void setTitle(String text) { + title.setText(text); + title.setVisibility(text != null ? VISIBLE : GONE); + } + public void setLocation(Location location, Connection.TransportType transportType) { + boolean valid = location.hasLocationInfo(); + locationText.setVisibility(valid ? VISIBLE : GONE); + locationIndicator.setVisibility(valid ? VISIBLE : GONE); + bridgesView.setVisibility(transportType == OBFS4 && location.supportsTransport(OBFS4) ? VISIBLE : GONE); + locationText.setText(location.getName()); + locationIndicator.setLoad(Load.getLoadByValue(location.getAverageLoad(transportType))); + selectedView.setChecked(location.selected); + } + + public void showDivider(boolean show) { + divider.setVisibility(show ? VISIBLE : GONE); + } + + public void setSelected(boolean selected) { + selectedView.setChecked(selected); + } + + public boolean isSelected() { + return selectedView.checkView.getVisibility() == VISIBLE; + } + +} diff --git a/app/src/main/java/se/leap/bitmaskclient/base/views/SimpleCheckBox.java b/app/src/main/java/se/leap/bitmaskclient/base/views/SimpleCheckBox.java new file mode 100644 index 00000000..09a9132e --- /dev/null +++ b/app/src/main/java/se/leap/bitmaskclient/base/views/SimpleCheckBox.java @@ -0,0 +1,73 @@ +package se.leap.bitmaskclient.base.views; + +import android.annotation.TargetApi; +import android.content.Context; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.RelativeLayout; + +import androidx.appcompat.widget.AppCompatImageView; + +import java.lang.ref.WeakReference; + +import se.leap.bitmaskclient.R; + +public class SimpleCheckBox extends RelativeLayout { + + AppCompatImageView checkView; + private WeakReference<OnCheckedChangeListener> checkedChangeListener = new WeakReference<OnCheckedChangeListener>(null); + private boolean checked; + + public interface OnCheckedChangeListener { + void onCheckedChanged(SimpleCheckBox simpleCheckBox, boolean isChecked); + } + + + public SimpleCheckBox(Context context) { + super(context); + initLayout(context); + } + + public SimpleCheckBox(Context context, AttributeSet attrs) { + super(context, attrs); + initLayout(context); + } + + public SimpleCheckBox(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initLayout(context); + } + + @TargetApi(21) + public SimpleCheckBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + initLayout(context); + } + + private void initLayout(Context context) { + LayoutInflater inflater = (LayoutInflater) context + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View rootview = inflater.inflate(R.layout.v_simple_checkbox, this, true); + this.checkView = rootview.findViewById(R.id.check_view); + } + + public void setChecked(boolean checked) { + if (this.checked != checked) { + this.checkView.setVisibility(checked ? VISIBLE : INVISIBLE); + this.checked = checked; + OnCheckedChangeListener listener = checkedChangeListener.get(); + if (listener != null) { + listener.onCheckedChanged(this, this.checked); + } + } + } + + public void setOnCheckedChangeListener(OnCheckedChangeListener listener) { + checkedChangeListener = new WeakReference<>(listener); + } + + public void toggle() { + setChecked(!this.checked); + } +} 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 dd9054f1..a7e08bd7 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/EIP.java @@ -127,7 +127,8 @@ public final class EIP extends JobIntentService implements Observer { ERROR_INVALID_VPN_CERTIFICATE, NO_MORE_GATEWAYS, ERROR_VPN_PREPARE, - ERROR_INVALID_PROFILE + ERROR_INVALID_PROFILE, + TRANSPORT_NOT_SUPPORTED, } /** diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/Gateway.java b/app/src/main/java/se/leap/bitmaskclient/eip/Gateway.java index 78b33355..a3d3abbc 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/Gateway.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/Gateway.java @@ -33,6 +33,7 @@ import java.util.Set; import de.blinkt.openvpn.VpnProfile; import de.blinkt.openvpn.core.ConfigParser; import de.blinkt.openvpn.core.connection.Connection; +import se.leap.bitmaskclient.base.utils.ConfigHelper; import se.leap.bitmaskclient.base.utils.PreferenceHelper; import static se.leap.bitmaskclient.base.models.Constants.FULLNESS; @@ -156,7 +157,7 @@ public class Gateway { try { return load.getDouble(FULLNESS); } catch (JSONException | NullPointerException e) { - return 0; + return ConfigHelper.getConnectionQualityFromTimezoneDistance(timezone); } } @@ -195,6 +196,10 @@ public class Gateway { return vpnProfiles.get(transportType) != null; } + public HashSet<Connection.TransportType> getSupportedTransports() { + return new HashSet<>(vpnProfiles.keySet()); + } + public int getTimezone() { return timezone; } diff --git a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaySelector.java b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaySelector.java index 33fd3c21..52030ce3 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaySelector.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaySelector.java @@ -2,6 +2,8 @@ package se.leap.bitmaskclient.eip; import android.util.Log; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -9,6 +11,7 @@ import java.util.Set; import java.util.TreeMap; import static se.leap.bitmaskclient.base.utils.ConfigHelper.getCurrentTimezone; +import static se.leap.bitmaskclient.base.utils.ConfigHelper.timezoneDistance; public class GatewaySelector { private final static String TAG = GatewaySelector.class.getSimpleName(); @@ -18,7 +21,15 @@ public class GatewaySelector { public GatewaySelector(List<Gateway> gateways) { this.gateways = gateways; this.offsets = calculateOffsets(); + } + public ArrayList<Gateway> getGatewaysSortedByDistance() { + ArrayList<Gateway> list = new ArrayList<>(); + int i = 0; + for (Collection<Gateway> gatewayCollection : offsets.values()) { + list.addAll(gatewayCollection); + } + return list; } public Gateway select() { @@ -57,12 +68,4 @@ public class GatewaySelector { return offsets; } - private int timezoneDistance(int local_timezone, int remote_timezone) { - // Distance along the numberline of Prime Meridian centric, assumes UTC-11 through UTC+12 - int dist = Math.abs(local_timezone - remote_timezone); - // Farther than 12 timezones and it's shorter around the "back" - if (dist > 12) - dist = 12 - (dist - 12); // Well i'll be. Absolute values make equations do funny things. - return dist; - } } 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 05775d13..060e69f2 100644 --- a/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java +++ b/app/src/main/java/se/leap/bitmaskclient/eip/GatewaysManager.java @@ -31,6 +31,7 @@ import org.json.JSONObject; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -39,6 +40,7 @@ import de.blinkt.openvpn.VpnProfile; import de.blinkt.openvpn.core.ConfigParser; import de.blinkt.openvpn.core.VpnStatus; import de.blinkt.openvpn.core.connection.Connection; +import de.blinkt.openvpn.core.connection.Connection.TransportType; import se.leap.bitmaskclient.base.models.Location; import se.leap.bitmaskclient.base.models.Provider; import se.leap.bitmaskclient.base.models.ProviderObservable; @@ -59,12 +61,45 @@ import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getUseBridges; */ public class GatewaysManager { + public enum Load { + UNKNOWN(0), + GOOD(0.25), + AVERAGE(0.75), + CRITICAL(1.0); + + private final double value; + + Load(double i) { + value = i; + } + + public static Load getLoadByValue(double value) { + if (value == UNKNOWN.value) { + return UNKNOWN; + } else if (value <= GOOD.value) { + return GOOD; + } else if (value <= AVERAGE.value) { + return AVERAGE; + } else if (value <= CRITICAL.value) { + return CRITICAL; + } else { + return UNKNOWN; + } + } + + public double getValue() { + return value; + } + } + private static final String TAG = GatewaysManager.class.getSimpleName(); - private Context context; - private LinkedHashMap<String, Gateway> gateways = new LinkedHashMap<>(); - private Type listType = new TypeToken<ArrayList<Gateway>>() {}.getType(); - private ArrayList<Gateway> presortedList = new ArrayList<>(); + private final Context context; + private final LinkedHashMap<String, Gateway> gateways = new LinkedHashMap<>(); + private final Type listType = new TypeToken<ArrayList<Gateway>>() {}.getType(); + private final ArrayList<Gateway> presortedList = new ArrayList<>(); + private ArrayList<Location> locations = new ArrayList<>(); + private TransportType selectedTransport; public GatewaysManager(Context context) { this.context = context; @@ -81,7 +116,7 @@ public class GatewaysManager { } public Gateway select(int nClosest, String city) { - Connection.TransportType transportType = getUseBridges(context) ? OBFS4 : OPENVPN; + TransportType transportType = getUseBridges(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType, city); } @@ -89,35 +124,97 @@ public class GatewaysManager { return getGatewayFromTimezoneCalculation(nClosest, transportType, city); } + public void updateTransport(TransportType transportType) { + if (this.selectedTransport == null || transportType != this.selectedTransport) { + this.selectedTransport = transportType; + locations.clear(); + } + } + public List<Location> getGatewayLocations() { - String selectedCity = PreferenceHelper.getPreferredCity(context); + return getSortedGatewayLocations(null); + } + + public List<Location> getSortedGatewayLocations(@Nullable TransportType selectedTransport) { + if (locations.size() > 0) { + return locations; + } + HashMap<String, Integer> locationNames = new HashMap<>(); ArrayList<Location> locations = new ArrayList<>(); - int n = 0; - Gateway gateway; - while ((gateway = select(n, null)) != null) { - if (!locationNames.containsKey(gateway.getName())) { - locationNames.put(gateway.getName(), locations.size()); - Location location = new Location( - gateway.getName(), - gateway.getFullness(), - 1, - gateway.getName().equals(selectedCity)); + String preferredCity = PreferenceHelper.getPreferredCity(context); + for (Gateway gateway : gateways.values()) { + String name = gateway.getName(); + if (name == null) { + Log.e(TAG, "Gateway without location name found. This should never happen. Provider misconfigured?"); + continue; + } + + if (!locationNames.containsKey(name)) { + locationNames.put(name, locations.size()); + Location location = initLocation(name, gateway, preferredCity); locations.add(location); } else { int index = locationNames.get(gateway.getName()); Location location = locations.get(index); - location.averageLoad = (location.numberOfGateways * location.averageLoad + gateway.getFullness()) / (location.numberOfGateways + 1); - location.numberOfGateways += 1; + updateLocation(location, gateway, OBFS4); + updateLocation(location, gateway, OPENVPN); locations.set(index, location); } - n++; } - + if (selectedTransport != null) { + Collections.sort(locations, new Location.SortByAverageLoad(selectedTransport)); + this.locations = locations; + } return locations; } - private Gateway getGatewayFromTimezoneCalculation(int nClosest, Connection.TransportType transportType, @Nullable String city) { + private Location initLocation(String name, Gateway gateway, String preferredCity) { + HashMap<TransportType, Double> averageLoadMap = new HashMap<>(); + HashMap<TransportType, Integer> numberOfGatewaysMap = new HashMap<>(); + if (gateway.getSupportedTransports().contains(OBFS4)) { + averageLoadMap.put(OBFS4, gateway.getFullness()); + numberOfGatewaysMap.put(OBFS4, 1); + } + if (gateway.getSupportedTransports().contains(OPENVPN)) { + averageLoadMap.put(OPENVPN, gateway.getFullness()); + numberOfGatewaysMap.put(OPENVPN, 1); + } + return new Location( + name, + averageLoadMap, + numberOfGatewaysMap, + name.equals(preferredCity)); + } + + private void updateLocation(Location location, Gateway gateway, Connection.TransportType transportType) { + if (gateway.getSupportedTransports().contains(transportType)) { + double averageLoad = location.getAverageLoad(transportType); + int numberOfGateways = location.getNumberOfGateways(transportType); + averageLoad = (numberOfGateways * averageLoad + gateway.getFullness()) / (numberOfGateways + 1); + numberOfGateways++; + location.setAverageLoad(transportType, averageLoad); + location.setNumberOfGateways(transportType, numberOfGateways); + } + } + + @Nullable + public Location getLocation(String name) { + List <Location> locations = getGatewayLocations(); + for (Location location : locations) { + if (location.getName().equals(name)) { + return location; + } + } + return null; + } + + public Load getLoadForLocation(@Nullable String name, TransportType transportType) { + Location location = getLocation(name); + return Load.getLoadByValue(location.getAverageLoad(transportType)); + } + + private Gateway getGatewayFromTimezoneCalculation(int nClosest, TransportType transportType, @Nullable String city) { List<Gateway> list = new ArrayList<>(gateways.values()); GatewaySelector gatewaySelector = new GatewaySelector(list); Gateway gateway; @@ -136,7 +233,7 @@ public class GatewaysManager { return null; } - private Gateway getGatewayFromPresortedList(int nClosest, Connection.TransportType transportType, @Nullable String city) { + private Gateway getGatewayFromPresortedList(int nClosest, TransportType transportType, @Nullable String city) { int found = 0; for (Gateway gateway : presortedList) { if ((city == null && gateway.supportsTransport(transportType)) || @@ -164,7 +261,7 @@ public class GatewaysManager { } private int getPositionFromPresortedList(VpnProfile profile) { - Connection.TransportType transportType = profile.mUsePluggableTransports ? OBFS4 : OPENVPN; + TransportType transportType = profile.mUsePluggableTransports ? OBFS4 : OPENVPN; int nClosest = 0; for (Gateway gateway : presortedList) { if (gateway.supportsTransport(transportType)) { @@ -178,7 +275,7 @@ public class GatewaysManager { } private int getPositionFromTimezoneCalculatedList(VpnProfile profile) { - Connection.TransportType transportType = profile.mUsePluggableTransports ? OBFS4 : OPENVPN; + TransportType transportType = profile.mUsePluggableTransports ? OBFS4 : OPENVPN; GatewaySelector gatewaySelector = new GatewaySelector(new ArrayList<>(gateways.values())); Gateway gateway; int nClosest = 0; @@ -326,4 +423,6 @@ public class GatewaysManager { } } + + } diff --git a/app/src/main/java/se/leap/bitmaskclient/providersetup/ProviderRenderer.java b/app/src/main/java/se/leap/bitmaskclient/providersetup/ProviderRenderer.java index 339199e0..8aba4941 100644 --- a/app/src/main/java/se/leap/bitmaskclient/providersetup/ProviderRenderer.java +++ b/app/src/main/java/se/leap/bitmaskclient/providersetup/ProviderRenderer.java @@ -4,7 +4,8 @@ import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.TextView; + +import androidx.appcompat.widget.AppCompatTextView; import com.pedrogomez.renderers.Renderer; @@ -20,9 +21,9 @@ public class ProviderRenderer extends Renderer<Provider> { private final Context context; @BindView(R.id.provider_name) - TextView name; + AppCompatTextView name; @BindView(R.id.provider_domain) - TextView domain; + AppCompatTextView domain; public ProviderRenderer(Context context) { this.context = context; diff --git a/app/src/main/java/se/leap/bitmaskclient/providersetup/activities/AbstractProviderDetailActivity.java b/app/src/main/java/se/leap/bitmaskclient/providersetup/activities/AbstractProviderDetailActivity.java index ba84ed9a..66999580 100644 --- a/app/src/main/java/se/leap/bitmaskclient/providersetup/activities/AbstractProviderDetailActivity.java +++ b/app/src/main/java/se/leap/bitmaskclient/providersetup/activities/AbstractProviderDetailActivity.java @@ -62,7 +62,7 @@ public abstract class AbstractProviderDetailActivity extends ConfigWizardBaseAct optionsList.toArray(new String[optionsList.size()]) )); options.setOnItemClickListener((parent, view, position, id) -> { - String text = ((TextView) view).getText().toString(); + String text = ((AppCompatTextView) view).getText().toString(); Intent intent; if (text.equals(getString(R.string.login_to_profile))) { Log.d(TAG, "login selected"); |