Skip to content

Commit

Permalink
Issue #493 several network connection fixes for older devices
Browse files Browse the repository at this point in the history
  • Loading branch information
yeriomin committed Jun 27, 2018
1 parent d8b5e9c commit dde6948
Show file tree
Hide file tree
Showing 14 changed files with 51 additions and 63 deletions.
Expand Up @@ -27,7 +27,7 @@
import android.widget.ImageView;

import com.github.yeriomin.yalpstore.DetailsActivity;
import com.github.yeriomin.yalpstore.NetworkState;
import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.R;
import com.github.yeriomin.yalpstore.fragment.Abstract;
import com.github.yeriomin.yalpstore.model.App;
Expand All @@ -51,7 +51,7 @@ public void draw() {
View background = activity.findViewById(R.id.background);
CollapsingToolbarLayout collapsingToolbarLayout = activity.findViewById(R.id.collapsing_toolbar_layout);
collapsingToolbarLayout.setExpandedTitleColor(activity.getResources().getColor(android.R.color.transparent));
if (!NetworkState.isNetworkAvailable(activity) || (!app.isInPlayStore() && !TextUtils.isEmpty(app.getDeveloperName()) && null == app.getPageBackgroundImage())) {
if (!NetworkUtil.isNetworkAvailable(activity) || (!app.isInPlayStore() && !TextUtils.isEmpty(app.getDeveloperName()) && null == app.getPageBackgroundImage())) {
collapsingToolbarLayout.setTitleEnabled(false);
collapsingToolbarLayout.getLayoutParams().height = CollapsingToolbarLayout.LayoutParams.MATCH_PARENT;
background.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
Expand Down
Expand Up @@ -34,9 +34,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import info.guardianproject.netcipher.NetCipher;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class BitmapManager {
Expand All @@ -59,7 +56,7 @@ protected int sizeOf(String key, Bitmap bitmap) {

public BitmapManager(Context context) {
baseDir = context.getCacheDir();
noImages = PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_NO_IMAGES) && NetworkState.isMetered(context);
noImages = PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_NO_IMAGES) && NetworkUtil.isMetered(context);
}

public Bitmap getBitmap(String url, boolean fullSize) {
Expand Down Expand Up @@ -146,10 +143,7 @@ static private void cacheBitmapInMemory(String url, Bitmap bitmap) {
static private Bitmap downloadBitmap(String url, boolean fullSize) {
InputStream input = null;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(Thread.currentThread().hashCode());
}
HttpURLConnection connection = NetCipher.getHttpURLConnection(new URL(url), true);
HttpURLConnection connection = NetworkUtil.getHttpURLConnection(url);
connection.connect();
connection.setConnectTimeout(3000);
input = connection.getInputStream();
Expand Down
Expand Up @@ -19,7 +19,6 @@

package com.github.yeriomin.yalpstore;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
Expand All @@ -36,8 +35,7 @@ public class DebugHttpClientAdapter extends NativeHttpClientAdapter {
static private final String DEBUG_DIRECTORY = "yalp-store-debug";
static private File dumpDirectory;

public DebugHttpClientAdapter(Context context) {
super(context);
public DebugHttpClientAdapter() {
dumpDirectory = new File(Environment.getExternalStorageDirectory(), DEBUG_DIRECTORY);
dumpDirectory.mkdirs();
}
Expand Down
Expand Up @@ -59,6 +59,6 @@ static private boolean nougatVpn(Context context) {
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) {
return false;
}
return NetworkState.isVpn(context);
return NetworkUtil.isVpn(context);
}
}
Expand Up @@ -19,8 +19,6 @@

package com.github.yeriomin.yalpstore;

import android.content.Context;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
Expand All @@ -38,37 +36,24 @@
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import info.guardianproject.netcipher.NetCipher;
import info.guardianproject.netcipher.client.StrongConnectionBuilder;

public class NativeHttpClientAdapter extends HttpClientAdapter {

static private final int TIMEOUT = 15000;
static private final int BUFFER_SIZE = 8192;

static {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}

protected StrongConnectionBuilder builder;

public NativeHttpClientAdapter(Context context) {
try {
builder = StrongConnectionBuilder.forMaxSecurity(context);
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Could build connection: " + e.getMessage());
}
}

@Override
public byte[] get(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
return request(getHttpURLConnection(buildUrl(url, params)), null, headers);
Expand Down Expand Up @@ -121,15 +106,13 @@ public String buildUrlEx(String url, Map<String, List<String>> params) {
}

protected HttpURLConnection getHttpURLConnection(String url) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(Thread.currentThread().hashCode());
}
return NetCipher.getHttpURLConnection(new URL(url), true);
return NetworkUtil.getHttpURLConnection(url);
}

protected byte[] request(HttpURLConnection connection, byte[] body, Map<String, String> headers) throws IOException {
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.addRequestProperty("Cache-Control", "max-age=300");
for (String headerName: headers.keySet()) {
Expand Down Expand Up @@ -225,8 +208,8 @@ static private byte[] readFully(InputStream inputStream, boolean gzipped) throws
if (gzipped) {
inputStream = new GZIPInputStream(inputStream);
}
InputStream bufferedInputStream = new BufferedInputStream(inputStream);
byte[] buffer = new byte[8192];
InputStream bufferedInputStream = new BufferedInputStream(inputStream, BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
Expand Down
Expand Up @@ -23,13 +23,19 @@
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.os.Build;
import android.util.Log;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Collections;

import info.guardianproject.netcipher.NetCipher;

import static android.content.Context.CONNECTIVITY_SERVICE;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
Expand All @@ -39,7 +45,21 @@
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;

public class NetworkState {
public class NetworkUtil {

static public HttpURLConnection getHttpURLConnection(String url) throws IOException {
return getHttpURLConnection(new URL(url));
}

static public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(Thread.currentThread().hashCode());
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return (HttpURLConnection) url.openConnection();
}
return NetCipher.getHttpURLConnection(url, true);
}

static public boolean isNetworkAvailable(Context context) {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
Expand Down Expand Up @@ -75,7 +95,7 @@ static private boolean isVpnHoneycomb() {
try {
for (NetworkInterface ni: Collections.list(NetworkInterface.getNetworkInterfaces())) {
if (ni.isUp() && (ni.getName().startsWith("tun") || ni.getName().startsWith("ppp"))) {
Log.i(NetworkState.class.getSimpleName(), "VPN seems to be on: " + ni.getName());
Log.i(NetworkUtil.class.getSimpleName(), "VPN seems to be on: " + ni.getName());
return true;
}
}
Expand Down
Expand Up @@ -154,7 +154,7 @@ private GooglePlayAPI build(LoginInfo loginInfo, int retries) throws IOException
// Impossible, unless there are mistakes, so no need to make it a declared exception
throw new RuntimeException(e);
} catch (AuthException | TokenDispenserException e) {
if (PlayStoreTask.noNetwork(e.getCause()) && !NetworkState.isNetworkAvailable(context)) {
if (PlayStoreTask.noNetwork(e.getCause()) && !NetworkUtil.isNetworkAvailable(context)) {
throw (IOException) e.getCause();
}
loginInfo.setTokenDispenserUrl(null);
Expand All @@ -176,7 +176,7 @@ private GooglePlayAPI build(LoginInfo loginInfo, int retries) throws IOException
private com.github.yeriomin.playstoreapi.PlayStoreApiBuilder getBuilder(LoginInfo loginInfo) {
fill(loginInfo);
return new com.github.yeriomin.playstoreapi.PlayStoreApiBuilder()
.setHttpClient(BuildConfig.DEBUG ? new DebugHttpClientAdapter(context) : new NativeHttpClientAdapter(context))
.setHttpClient(BuildConfig.DEBUG ? new DebugHttpClientAdapter() : new NativeHttpClientAdapter())
.setDeviceInfoProvider(getDeviceInfoProvider())
.setLocale(loginInfo.getLocale())
.setEmail(loginInfo.getEmail())
Expand Down
Expand Up @@ -93,7 +93,7 @@ private Properties getProperties(JarFile jarFile, JarEntry entry) {
private Properties getProperties(File file) {
Properties properties = new Properties();
try {
properties.load(new BufferedInputStream(new FileInputStream(file)));
properties.load(new BufferedInputStream(new FileInputStream(file), 8192));
} catch (IOException e) {
Log.e(getClass().getSimpleName(), "Could not read " + file.getName());
}
Expand Down
Expand Up @@ -98,7 +98,7 @@ public void clearPendingUpdates() {
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (!BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
HttpResponseCache.install(new File(getCacheDir(), "http"), 5 * 1024 * 1024);
} catch (IOException e) {
Expand Down Expand Up @@ -147,6 +147,9 @@ private void registerInstallReceiver() {
}

public void initNetcipher() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return;
}
listener = new ProxyOnChangeListener(this);
PreferenceUtil.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(listener);
Proxy proxy = PreferenceUtil.getProxy(this);
Expand Down
Expand Up @@ -25,15 +25,14 @@
import android.os.Build;

import com.github.yeriomin.yalpstore.BuildConfig;
import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.PreferenceUtil;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import info.guardianproject.netcipher.NetCipher;

abstract public class Updater {

static private final String CACHED_VERSION_CODE = "CACHED_VERSION_CODE";
Expand Down Expand Up @@ -90,10 +89,7 @@ private boolean isAvailable(int versionCode) {
if (null == url) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(Thread.currentThread().hashCode());
}
HttpURLConnection connection = NetCipher.getHttpURLConnection(url, true);
HttpURLConnection connection = NetworkUtil.getHttpURLConnection(url);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("HEAD");
return connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST;
Expand Down
Expand Up @@ -25,6 +25,7 @@
import android.text.format.DateUtils;
import android.util.Log;

import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.Util;
import com.github.yeriomin.yalpstore.YalpStoreApplication;

Expand All @@ -44,7 +45,6 @@
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import info.guardianproject.netcipher.NetCipher;

public class FdroidListTask extends TaskWithProgress<Void> {

Expand Down Expand Up @@ -76,7 +76,7 @@ protected Void doInBackground(String... strings) {
private void downloadXml() {
try {
URL url = new URL(FDROID_REPO_URL);
NetCipher.getHttpsURLConnection(url, true).connect();
NetworkUtil.getHttpURLConnection(url).connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(localXmlFile);
byte data[] = new byte[1024];
Expand Down
Expand Up @@ -22,7 +22,6 @@
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
Expand All @@ -32,6 +31,7 @@
import com.github.yeriomin.yalpstore.DownloadManagerFake;
import com.github.yeriomin.yalpstore.DownloadManagerInterface;
import com.github.yeriomin.yalpstore.DownloadState;
import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.R;
import com.github.yeriomin.yalpstore.Util;
import com.github.yeriomin.yalpstore.notification.CancelDownloadService;
Expand All @@ -45,12 +45,9 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import info.guardianproject.netcipher.NetCipher;

public class HttpURLConnectionDownloadTask extends AsyncTask<String, Long, Boolean> {

static private final String EXTENSION_OBB = ".obb";
Expand Down Expand Up @@ -115,10 +112,7 @@ protected Boolean doInBackground(String... params) {
InputStream in;
long fileSize;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(Thread.currentThread().hashCode());
}
connection = NetCipher.getHttpURLConnection(new URL(params[0]), true);
connection = NetworkUtil.getHttpURLConnection(params[0]);
if (params.length == 2 && !TextUtils.isEmpty(params[1])) {
connection.addRequestProperty("Cookie", params[1]);
}
Expand Down
Expand Up @@ -31,7 +31,7 @@
import android.widget.ImageView;

import com.github.yeriomin.yalpstore.BitmapManager;
import com.github.yeriomin.yalpstore.NetworkState;
import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.PreferenceUtil;
import com.github.yeriomin.yalpstore.R;
import com.github.yeriomin.yalpstore.model.ImageSource;
Expand Down Expand Up @@ -141,7 +141,7 @@ private void fadeOut() {
}

private boolean noImages() {
return NetworkState.isMetered(imageView.getContext()) && PreferenceUtil.getBoolean(imageView.getContext(), PreferenceUtil.PREFERENCE_NO_IMAGES);
return NetworkUtil.isMetered(imageView.getContext()) && PreferenceUtil.getBoolean(imageView.getContext(), PreferenceUtil.PREFERENCE_NO_IMAGES);
}

private boolean sameAsLoaded() {
Expand Down
Expand Up @@ -32,7 +32,7 @@
import com.github.yeriomin.yalpstore.DownloadState;
import com.github.yeriomin.yalpstore.InstallerAbstract;
import com.github.yeriomin.yalpstore.InstallerFactory;
import com.github.yeriomin.yalpstore.NetworkState;
import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.Paths;
import com.github.yeriomin.yalpstore.PreferenceUtil;
import com.github.yeriomin.yalpstore.R;
Expand Down Expand Up @@ -93,7 +93,7 @@ private boolean canUpdate() {
(PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_BACKGROUND_UPDATE_DOWNLOAD)
&& (DownloadManagerFactory.get(context) instanceof DownloadManagerAdapter
|| !PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_BACKGROUND_UPDATE_WIFI_ONLY)
|| !NetworkState.isMetered(context)
|| !NetworkUtil.isMetered(context)
)
)
;
Expand Down

0 comments on commit dde6948

Please sign in to comment.