about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--org.fox.ttrss/src/main/java/org/fox/ttrss/ApiCommon.java138
-rw-r--r--org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java125
-rw-r--r--org.fox.ttrss/src/main/java/org/fox/ttrss/OkHttpFactory.java194
3 files changed, 200 insertions, 257 deletions
diff --git a/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiCommon.java b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiCommon.java
index 0a3bce10..6b76048b 100644
--- a/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiCommon.java
+++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiCommon.java
@@ -8,8 +8,6 @@ import android.content.pm.PackageManager;
 import android.content.res.AssetFileDescriptor;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
-import android.security.KeyChain;
-import android.security.KeyChainException;
 import android.util.Log;
 
 import androidx.annotation.NonNull;
@@ -20,39 +18,18 @@ import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
 
-import org.fox.ttrss.util.KeyChainKeyManager;
-
-import java.io.FileInputStream;
 import java.io.IOException;
-import java.io.InputStream;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
 import java.util.HashMap;
 import java.util.Locale;
 import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
 
 import okhttp3.Credentials;
 import okhttp3.HttpUrl;
-import okhttp3.Interceptor;
 import okhttp3.MediaType;
 import okhttp3.OkHttpClient;
 import okhttp3.Request;
 import okhttp3.RequestBody;
 import okhttp3.Response;
-import okhttp3.ResponseBody;
-import okio.Buffer;
-import okio.BufferedSource;
-import okio.ForwardingSource;
-import okio.Okio;
-import okio.Source;
 
 public class ApiCommon {
     public static final String TAG = "ApiCommon";
@@ -435,53 +412,14 @@ public class ApiCommon {
 
             Request request = requestBuilder.build();
 
-            ResponseProgressListener listener = new ResponseProgressListener() {
-                @Override
-                public void update(HttpUrl url, long bytesRead, long contentLength) {
-                    // Log.d(TAG, "[progress] " + url + " " + bytesRead + " of " + contentLength);
+            OkHttpFactory.ProgressListener listener = (url, bytesRead, contentLength) -> {
+                // Log.d(TAG, "[progress] " + url + " " + bytesRead + " of " + contentLength);
 
-                    if (contentLength > 0)
-                        caller.notifyProgress((int) (bytesRead * 100f / contentLength));
-                }
+                if (contentLength > 0)
+                    caller.notifyProgress((int) (bytesRead * 100f / contentLength));
             };
 
-            /* lets shamelessly hijack OkHttpProgressGlideModule */
-
-            OkHttpClient.Builder builder = new OkHttpClient.Builder()
-                .connectTimeout(10, TimeUnit.SECONDS)
-                .writeTimeout(10, TimeUnit.SECONDS)
-                .readTimeout(30, TimeUnit.SECONDS)
-                .addNetworkInterceptor(createInterceptor(listener));
-
-            String clientCertAlias = m_prefs.getString("mtls_certificate_alias", null);
-
-            if (m_prefs.getBoolean("mtls_enabled", false) && clientCertAlias != null) {
-                try {
-                    X509Certificate[] chain = KeyChain.getCertificateChain(context, clientCertAlias);
-                    PrivateKey privateKey = KeyChain.getPrivateKey(context, clientCertAlias);
-
-                    KeyManager[] keyManagers = new KeyManager[]{new KeyChainKeyManager(clientCertAlias, chain, privateKey)};
-
-                    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
-
-                    // we don't need custom CA
-                    trustManagerFactory.init((KeyStore) null);
-                    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
-
-                    SSLContext sslContext = SSLContext.getInstance("TLS");
-                    sslContext.init(keyManagers, trustManagers, null);
-
-                    // enable mtls in okhttp3 builder
-                    builder.sslSocketFactory(sslContext.getSocketFactory());
-                } catch (Exception e) {
-                    Log.e(TAG, "configuring mTLS", e);
-
-                    caller.setLastErrorMessage(e.getMessage());
-                    caller.setLastError(ApiError.API_UNKNOWN);
-                }
-            }
-
-            OkHttpClient client = builder.build();
+            OkHttpClient client = OkHttpFactory.createClient(context, listener, caller);
 
             try (Response response = client.newCall(request).execute()) {
                 if (response.isSuccessful()) {
@@ -584,72 +522,6 @@ public class ApiCommon {
         return null;
     }
 
-    private interface ResponseProgressListener {
-        void update(HttpUrl url, long bytesRead, long contentLength);
-    }
-
-    private static Interceptor createInterceptor(final ResponseProgressListener listener) {
-        return chain -> {
-            Request request = chain.request();
-            Response response = chain.proceed(request);
-            return response.newBuilder()
-                    .body(new ProgressResponseBody(request.url(), response.body(), listener))
-                    .build();
-        };
-    }
-
-    private static class ProgressResponseBody extends ResponseBody {
-        private final HttpUrl url;
-        private final ResponseBody responseBody;
-        private final ResponseProgressListener progressListener;
-        private BufferedSource bufferedSource;
-
-        public ProgressResponseBody(HttpUrl url, ResponseBody responseBody,
-                                    ResponseProgressListener progressListener) {
-
-            this.url = url;
-            this.responseBody = responseBody;
-            this.progressListener = progressListener;
-        }
-
-        @Override
-        public MediaType contentType() {
-            return responseBody.contentType();
-        }
-
-        @Override
-        public long contentLength() {
-            return responseBody.contentLength();
-        }
-
-        @Override
-        public BufferedSource source() {
-            if (bufferedSource == null) {
-                bufferedSource = Okio.buffer(source(responseBody.source()));
-            }
-            return bufferedSource;
-        }
-
-        private Source source(Source source) {
-            return new ForwardingSource(source) {
-                long totalBytesRead = 0L;
-
-                @Override
-                public long read(Buffer sink, long byteCount) throws IOException {
-                    long bytesRead = super.read(sink, byteCount);
-                    long fullLength = responseBody.contentLength();
-                    if (bytesRead == -1) { // this source is exhausted
-                        totalBytesRead = fullLength;
-                    } else {
-                        totalBytesRead += bytesRead;
-                    }
-                    progressListener.update(url, totalBytesRead, fullLength);
-                    return bytesRead;
-                }
-            };
-        }
-    }
-
     private static String getUserAgent(Context context) {
         try {
             PackageInfo packageInfo = context.getPackageManager().
diff --git a/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java
index 863f56a5..4debd418 100644
--- a/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java
+++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java
@@ -12,35 +12,19 @@ import com.google.gson.Gson;
 import com.google.gson.JsonElement;
 
 import org.fox.ttrss.ApiCommon.ApiError;
-import org.fox.ttrss.util.KeyChainKeyManager;
 
 import java.io.IOException;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
 import java.util.Locale;
 import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
 
 import okhttp3.Credentials;
 import okhttp3.FormBody;
 import okhttp3.HttpUrl;
-import okhttp3.Interceptor;
 import okhttp3.MediaType;
 import okhttp3.OkHttpClient;
 import okhttp3.Request;
 import okhttp3.RequestBody;
 import okhttp3.Response;
-import okhttp3.ResponseBody;
-import okio.Buffer;
-import okio.BufferedSource;
-import okio.ForwardingSource;
-import okio.Okio;
-import okio.Source;
 
 /**
  * RESTful APIv2 client for tt-rss.
@@ -54,45 +38,7 @@ import okio.Source;
 public class ApiV2Client {
     public static final String TAG = "ApiV2Client";
 
-    /**
-     * Build an OkHttpClient with the given progress listener (or null for no progress).
-     * Handles mutual TLS if configured.
-     */
-    private static OkHttpClient buildClient(Context context, ProgressListener progressListener) {
-        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
-        OkHttpClient.Builder builder = new OkHttpClient.Builder()
-                .connectTimeout(10, TimeUnit.SECONDS)
-                .writeTimeout(10, TimeUnit.SECONDS)
-                .readTimeout(30, TimeUnit.SECONDS);
-
-        if (progressListener != null) {
-            builder.addNetworkInterceptor(createProgressInterceptor(progressListener));
-        }
-
-        if (prefs.getBoolean("mtls_enabled", false)) {
-            String clientCertAlias = prefs.getString("mtls_certificate_alias", null);
-            if (clientCertAlias != null) {
-                try {
-                    X509Certificate[] chain = android.security.KeyChain.getCertificateChain(context, clientCertAlias);
-                    PrivateKey privateKey = android.security.KeyChain.getPrivateKey(context, clientCertAlias);
-
-                    KeyManager[] keyManagers = new KeyManager[]{new KeyChainKeyManager(clientCertAlias, chain, privateKey)};
 
-                    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
-                    trustManagerFactory.init((java.security.KeyStore) null);
-                    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
-
-                    SSLContext sslContext = SSLContext.getInstance("TLS");
-                    sslContext.init(keyManagers, trustManagers, null);
-                    builder.sslSocketFactory(sslContext.getSocketFactory());
-                } catch (Exception e) {
-                    Log.e(TAG, "mTLS setup failed", e);
-                }
-            }
-        }
-
-        return builder.build();
-    }
 
     /**
      * Build the base URL for APIv2 requests.
@@ -235,7 +181,7 @@ public class ApiV2Client {
             }
 
             // Build client and execute
-            OkHttpClient client = buildClient(context, null);
+            OkHttpClient client = OkHttpFactory.createClient(context, null, null);
             Response response = client.newCall(requestBuilder.build()).execute();
 
             if (response.isSuccessful()) {
@@ -281,76 +227,7 @@ public class ApiV2Client {
         }
     }
 
-    // ─── Progress support ─────────────────────────────────────────────────────
-
-    /**
-     * Internal progress callback interface.
-     * Mirrors ApiCommon.ResponseProgressListener (which is private there).
-     */
-    private interface ProgressListener {
-        void update(HttpUrl url, long bytesRead, long contentLength);
-    }
-
-    private static Interceptor createProgressInterceptor(final ProgressListener listener) {
-        return chain -> {
-            Request request = chain.request();
-            Response response = chain.proceed(request);
-            return response.newBuilder()
-                    .body(new ProgressResponseBody(request.url(), response.body(), listener))
-                    .build();
-        };
-    }
-
-    private static class ProgressResponseBody extends ResponseBody {
-        private final HttpUrl url;
-        private final ResponseBody responseBody;
-        private final ProgressListener progressListener;
-        private BufferedSource bufferedSource;
-
-        public ProgressResponseBody(HttpUrl url, ResponseBody responseBody,
-                                    ProgressListener progressListener) {
-            this.url = url;
-            this.responseBody = responseBody;
-            this.progressListener = progressListener;
-        }
-
-        @Override
-        public MediaType contentType() {
-            return responseBody.contentType();
-        }
-
-        @Override
-        public long contentLength() {
-            return responseBody.contentLength();
-        }
-
-        @Override
-        public BufferedSource source() {
-            if (bufferedSource == null) {
-                bufferedSource = Okio.buffer(source(responseBody.source()));
-            }
-            return bufferedSource;
-        }
 
-        private Source source(Source source) {
-            return new ForwardingSource(source) {
-                long totalBytesRead = 0L;
-
-                @Override
-                public long read(Buffer sink, long byteCount) throws IOException {
-                    long bytesRead = super.read(sink, byteCount);
-                    long fullLength = responseBody.contentLength();
-                    if (bytesRead == -1) {
-                        totalBytesRead = fullLength;
-                    } else {
-                        totalBytesRead += bytesRead;
-                    }
-                    progressListener.update(url, totalBytesRead, fullLength);
-                    return bytesRead;
-                }
-            };
-        }
-    }
 
     // ─── Helpers ──────────────────────────────────────────────────────────────
 
diff --git a/org.fox.ttrss/src/main/java/org/fox/ttrss/OkHttpFactory.java b/org.fox.ttrss/src/main/java/org/fox/ttrss/OkHttpFactory.java
new file mode 100644
index 00000000..7922fbd1
--- /dev/null
+++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/OkHttpFactory.java
@@ -0,0 +1,194 @@
+package org.fox.ttrss;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.security.KeyChain;
+import android.security.KeyChainException;
+import android.util.Log;
+
+import androidx.preference.PreferenceManager;
+
+import org.fox.ttrss.ApiCommon.ApiError;
+import org.fox.ttrss.ApiCommon.ApiCaller;
+import org.fox.ttrss.util.KeyChainKeyManager;
+
+import java.io.IOException;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.util.concurrent.TimeUnit;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import okhttp3.Interceptor;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+import okio.Buffer;
+import okio.BufferedSource;
+import okio.ForwardingSource;
+import okio.Okio;
+import okio.Source;
+
+/**
+ * Shared OkHttp client factory.
+ *
+ * Centralizes mTLS configuration, timeouts, and progress interceptors
+ * so that ApiCommon (v1) and ApiV2Client (v2) don't duplicate the setup.
+ */
+public final class OkHttpFactory {
+    private static final String TAG = "OkHttpFactory";
+
+    private static final long CONNECT_TIMEOUT = 10;
+    private static final long WRITE_TIMEOUT = 10;
+    private static final long READ_TIMEOUT = 30;
+
+    /**
+     * Callback for download progress. Mirrors ApiCommon.ResponseProgressListener.
+     */
+    public interface ProgressListener {
+        void update(okhttp3.HttpUrl url, long bytesRead, long contentLength);
+    }
+
+    private OkHttpFactory() {
+        // no instances
+    }
+
+    /**
+     * Build an OkHttpClient with mTLS support and optional progress tracking.
+     *
+     * @param context             application context
+     * @param progressListener    progress callback (or null for no progress)
+     * @param caller              api caller for error reporting during mTLS setup
+     * @return configured OkHttpClient
+     */
+    public static OkHttpClient createClient(Context context, ProgressListener progressListener, ApiCaller caller) {
+        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+        OkHttpClient.Builder builder = new OkHttpClient.Builder()
+                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
+                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
+                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
+
+        if (progressListener != null) {
+            builder.addNetworkInterceptor(createProgressInterceptor(progressListener));
+        }
+
+        configureMtls(context, builder, caller);
+
+        return builder.build();
+    }
+
+    /**
+     * Configure mutual TLS on the OkHttpClient builder.
+     */
+    private static void configureMtls(Context context, OkHttpClient.Builder builder, ApiCaller caller) {
+        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+        if (!prefs.getBoolean("mtls_enabled", false)) {
+            return;
+        }
+
+        String clientCertAlias = prefs.getString("mtls_certificate_alias", null);
+        if (clientCertAlias == null) {
+            return;
+        }
+
+        try {
+            X509Certificate[] chain = KeyChain.getCertificateChain(context, clientCertAlias);
+            PrivateKey privateKey = KeyChain.getPrivateKey(context, clientCertAlias);
+
+            KeyManager[] keyManagers = new KeyManager[]{new KeyChainKeyManager(clientCertAlias, chain, privateKey)};
+
+            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+            trustManagerFactory.init((java.security.KeyStore) null);
+            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
+
+            SSLContext sslContext = SSLContext.getInstance("TLS");
+            sslContext.init(keyManagers, trustManagers, null);
+            builder.sslSocketFactory(sslContext.getSocketFactory());
+        } catch (KeyChainException | InterruptedException e) {
+            Log.e(TAG, "mTLS setup failed", e);
+            if (caller != null) {
+                caller.setLastErrorMessage(e.getMessage());
+                caller.setLastError(ApiError.API_UNKNOWN);
+            }
+        } catch (NoSuchAlgorithmException | java.security.KeyStoreException |
+                 java.security.KeyManagementException e) {
+            Log.e(TAG, "mTLS SSL setup failed", e);
+            if (caller != null) {
+                caller.setLastErrorMessage(e.getMessage());
+                caller.setLastError(ApiError.API_UNKNOWN);
+            }
+        }
+    }
+
+    /**
+     * Create an OkHttp interceptor that reports download progress.
+     */
+    private static Interceptor createProgressInterceptor(final ProgressListener listener) {
+        return chain -> {
+            Request request = chain.request();
+            Response response = chain.proceed(request);
+            return response.newBuilder()
+                    .body(new ProgressResponseBody(request.url(), response.body(), listener))
+                    .build();
+        };
+    }
+
+    /**
+     * ResponseBody wrapper that reports byte-level progress.
+     */
+    private static class ProgressResponseBody extends ResponseBody {
+        private final okhttp3.HttpUrl url;
+        private final ResponseBody responseBody;
+        private final ProgressListener progressListener;
+        private BufferedSource bufferedSource;
+
+        ProgressResponseBody(okhttp3.HttpUrl url, ResponseBody responseBody,
+                             ProgressListener progressListener) {
+            this.url = url;
+            this.responseBody = responseBody;
+            this.progressListener = progressListener;
+        }
+
+        @Override
+        public okhttp3.MediaType contentType() {
+            return responseBody.contentType();
+        }
+
+        @Override
+        public long contentLength() {
+            return responseBody.contentLength();
+        }
+
+        @Override
+        public BufferedSource source() {
+            if (bufferedSource == null) {
+                bufferedSource = Okio.buffer(source(responseBody.source()));
+            }
+            return bufferedSource;
+        }
+
+        private Source source(Source source) {
+            return new ForwardingSource(source) {
+                long totalBytesRead = 0L;
+
+                @Override
+                public long read(Buffer sink, long byteCount) throws IOException {
+                    long bytesRead = super.read(sink, byteCount);
+                    long fullLength = responseBody.contentLength();
+                    if (bytesRead == -1) {
+                        totalBytesRead = fullLength;
+                    } else {
+                        totalBytesRead += bytesRead;
+                    }
+                    progressListener.update(url, totalBytesRead, fullLength);
+                    return bytesRead;
+                }
+            };
+        }
+    }
+}