diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-06-06 09:28:50 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-06-06 09:28:50 +0300 |
| commit | ae7fe893d23e23bb3b3919472134616bf49372b7 (patch) | |
| tree | edd7fdddbd92dd116304edb35381c09511cfbd32 | |
| parent | b0502259a741696408223df81d03618f223ac1c5 (diff) | |
| download | tt-rss-android-ae7fe893d23e23bb3b3919472134616bf49372b7.tar.gz tt-rss-android-ae7fe893d23e23bb3b3919472134616bf49372b7.tar.xz | |
scaffold apiv2 client
5 files changed, 715 insertions, 2 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 70de409a..89152121 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 @@ -30,6 +30,7 @@ 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; @@ -56,6 +57,12 @@ import okio.Source; public class ApiCommon { public static final String TAG = "ApiCommon"; + /** + * SharedPreferences key for selecting API version. + * Values: "v1" (default), "v2", or "auto" (try v2, fall back to v1). + */ + public static final String PREF_API_VERSION = "api_version"; + private static final int API_STATUS_OK = 0; private static final int API_STATUS_ERR = 1; @@ -69,6 +76,8 @@ public class ApiCommon { void setLastErrorMessage(String message); void notifyProgress(int progress); + + ApiError getLastError(); } public enum ApiError { @@ -135,8 +144,258 @@ public class ApiCommon { return networkInfo != null && networkInfo.isConnected(); } + /** + * Get the configured API version from SharedPreferences. + * Returns "v1" if not set or invalid. + */ + static String getApiVersion(Context context) { + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + String version = prefs.getString(PREF_API_VERSION, "v1"); + if (!"v1".equals(version) && !"v2".equals(version) && !"auto".equals(version)) { + return "v1"; + } + return version; + } + + /** + * Dispatch a v1-style op-based request to the appropriate v2 endpoint. + * Returns JsonElement (the "data" field from v2 response) or null on error. + */ + private static JsonElement performRequestV2(Context context, @NonNull HashMap<String, String> m_params, + @NonNull ApiCommon.ApiCaller caller) { + String op = m_params.get("op"); + if (op == null) { + caller.setLastError(ApiError.API_UNKNOWN_METHOD); + return null; + } + + Map<String, String> queryParams = new HashMap<>(); + Map<String, String> bodyParams = new HashMap<>(); + + // Separate sid from params (v2 uses X-Session-ID header instead) + m_params.forEach((k, v) -> { + if (!"sid".equals(k)) { + if (v != null) { + bodyParams.put(k, v); + } + } + }); + + switch (op) { + // ── Auth ─────────────────────────────────────────────────────── + case "login": + return ApiV2Client.postForm(context, "auth/login", bodyParams, caller); + + case "logout": + return ApiV2Client.postForm(context, "auth/logout", bodyParams, caller); + + case "isLoggedIn": + return ApiV2Client.get(context, "auth/session", caller); + + // ── System ───────────────────────────────────────────────────── + case "getVersion": + return ApiV2Client.get(context, "version", caller); + + case "getApiLevel": + // v2 has no getApiLevel endpoint; use version and extract api_level + JsonElement versionResult = ApiV2Client.get(context, "version", caller); + if (versionResult != null && caller.getLastError() == ApiError.SUCCESS) { + // v2 version response may include api_level in data + return versionResult; + } + return null; + + case "getConfig": + return ApiV2Client.get(context, "config", caller); + + // ── Feeds ────────────────────────────────────────────────────── + case "getFeeds": + // cat_id, unread_only, limit, offset, include_nested → query params + queryParams.putAll(bodyParams); + bodyParams.clear(); + return ApiV2Client.get(context, "feeds", queryParams, caller); + + case "subscribeToFeed": + return ApiV2Client.postForm(context, "feeds", bodyParams, caller); + + case "unsubscribeFeed": + String feedId = bodyParams.get("feed_id"); + return ApiV2Client.delete(context, "feeds/" + feedId, caller); + + case "updateFeed": + String uid = bodyParams.get("feed_id"); + return ApiV2Client.postForm(context, "feeds/" + uid + "/update", bodyParams, caller); + + // ── Categories ───────────────────────────────────────────────── + case "getCategories": + // enable_nested → include_empty (semantic inversion in v2) + if (bodyParams.containsKey("enable_nested")) { + bodyParams.put("include_empty", bodyParams.get("enable_nested")); + bodyParams.remove("enable_nested"); + } + return ApiV2Client.get(context, "categories", bodyParams, caller); + + // ── Articles ─────────────────────────────────────────────────── + case "getHeadlines": + // feed_id, limit, skip, filter, is_cat, view_mode, etc. → query params + queryParams.putAll(bodyParams); + bodyParams.clear(); + return ApiV2Client.get(context, "articles", queryParams, caller); + + case "getArticle": + String articleIds = bodyParams.get("article_id"); + if (articleIds != null) { + return ApiV2Client.get(context, "articles/" + articleIds, caller); + } + caller.setLastError(ApiError.API_INCORRECT_USAGE); + return null; + + case "updateArticle": + // v1: field (int) + mode (int) + article_ids (csv) + data + // v2: batch PATCH with boolean flags per key + // Reconstruct v2 batch body from v1 params + Map<String, String> v2BatchBody = new HashMap<>(); + String articleIdsParam = bodyParams.get("article_ids"); + if (articleIdsParam != null) { + // Convert CSV to JSON array string for v2 + String[] ids = articleIdsParam.split(","); + StringBuilder idsJson = new StringBuilder("["); + for (int i = 0; i < ids.length; i++) { + if (i > 0) idsJson.append(","); + idsJson.append(ids[i].trim()); + } + idsJson.append("]"); + v2BatchBody.put("ids", idsJson.toString()); + } + + String fieldStr = bodyParams.get("field"); + String modeStr = bodyParams.get("mode"); + if (fieldStr != null && modeStr != null) { + int field = Integer.parseInt(fieldStr); + int mode = Integer.parseInt(modeStr); + + switch (field) { + case 0: // marked + v2BatchBody.put("marked", String.valueOf(mode == 1)); + break; + case 1: // published + v2BatchBody.put("published", String.valueOf(mode == 1)); + break; + case 2: // unread + v2BatchBody.put("unread", String.valueOf(mode == 1)); + break; + case 3: // note + v2BatchBody.put("note", bodyParams.getOrDefault("data", "")); + break; + case 4: // score + v2BatchBody.put("score", bodyParams.getOrDefault("data", "0")); + break; + } + } + return ApiV2Client.patchForm(context, "articles", v2BatchBody, caller); + + // ── Catchup ──────────────────────────────────────────────────── + case "catchupFeed": + String cfId = bodyParams.get("feed_id"); + return ApiV2Client.patchForm(context, "feeds/" + cfId + "/catchup", bodyParams, caller); + + // ── Labels ───────────────────────────────────────────────────── + case "getLabels": + // article_id → query param + if (bodyParams.containsKey("article_id")) { + queryParams.put("article_id", bodyParams.get("article_id")); + bodyParams.clear(); + } + return ApiV2Client.get(context, "labels", queryParams, caller); + + case "setArticleLabel": + // v1: label_id + article_ids (csv) + assign (bool) + // v2: POST /labels/{id}/articles with article_ids array + String labelId = bodyParams.get("label_id"); + String assign = bodyParams.get("assign"); + if (labelId == null) { + caller.setLastError(ApiError.API_INCORRECT_USAGE); + return null; + } + Map<String, String> labelBody = new HashMap<>(); + if ("true".equals(assign)) { + // Convert CSV to JSON array + String articleIdsLbl = bodyParams.get("article_ids"); + if (articleIdsLbl != null) { + String[] ids = articleIdsLbl.split(","); + StringBuilder idsJson = new StringBuilder("["); + for (int i = 0; i < ids.length; i++) { + if (i > 0) idsJson.append(","); + idsJson.append(ids[i].trim()); + } + idsJson.append("]"); + labelBody.put("article_ids", idsJson.toString()); + } + return ApiV2Client.postForm(context, "labels/" + labelId + "/articles", labelBody, caller); + } else { + return ApiV2Client.deleteForm(context, "labels/" + labelId + "/articles", labelBody, caller); + } + + // ── Unread / Counters / Feed Tree ────────────────────────────── + case "getUnread": + queryParams.putAll(bodyParams); + bodyParams.clear(); + return ApiV2Client.get(context, "unread", queryParams, caller); + + case "getCounters": + return ApiV2Client.get(context, "counters", caller); + + case "getFeedTree": + return ApiV2Client.get(context, "feed-tree", bodyParams, caller); + + // ── Preferences ──────────────────────────────────────────────── + case "getPref": + String prefName = bodyParams.get("pref_name"); + if (prefName != null) { + return ApiV2Client.get(context, "preferences/" + prefName, caller); + } + caller.setLastError(ApiError.API_INCORRECT_USAGE); + return null; + + // ── v1-only operations (no v2 equivalent) ────────────────────── + case "shareToPublished": + // v1-only operation; signal to fall back to v1 + Log.d(TAG, "shareToPublished has no v2 equivalent, falling back"); + caller.setLastError(ApiError.API_UNKNOWN_METHOD); + return null; + + // ── Unknown ──────────────────────────────────────────────────── + default: + Log.d(TAG, "Unknown APIv2 op: " + op); + caller.setLastError(ApiError.API_UNKNOWN_METHOD); + return null; + } + } + static JsonElement performRequest(Context context, @NonNull HashMap<String, String> m_params, @NonNull ApiCommon.ApiCaller caller) { + // Feature flag: delegate to v2 client if configured + String apiVersion = getApiVersion(context); + if ("v2".equals(apiVersion) || "auto".equals(apiVersion)) { + try { + JsonElement result = performRequestV2(context, m_params, caller); + if (result != null || caller.getLastError() != ApiError.NETWORK_UNAVAILABLE) { + return result; + } + // auto mode: fall through to v1 if v2 failed + if ("auto".equals(apiVersion)) { + Log.d(TAG, "APIv2 failed, falling back to v1"); + } + } catch (Exception e) { + Log.e(TAG, "APIv2 exception, falling back to v1: " + e.getMessage()); + if ("auto".equals(apiVersion)) { + // Continue to v1 + } else { + throw e; + } + } + } + try { if (!ApiCommon.isNetworkAvailable(context)) { caller.setLastError(ApiError.NETWORK_UNAVAILABLE); diff --git a/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiRequest.java b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiRequest.java index c213dd86..065a9dcb 100644 --- a/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiRequest.java +++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiRequest.java @@ -58,4 +58,9 @@ public class ApiRequest extends AsyncTask<HashMap<String, String>, Integer, Json public void notifyProgress(int progress) { publishProgress(progress); } + + @Override + public ApiError getLastError() { + return m_lastError; + } } 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 new file mode 100644 index 00000000..d424d98f --- /dev/null +++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java @@ -0,0 +1,449 @@ +package org.fox.ttrss; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.util.Log; + +import androidx.preference.PreferenceManager; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +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. + * + * Replaces the old v1 "op-based" POST /api/ endpoint with proper HTTP methods + * and X-Session-ID header authentication. + * + * Response format: {"success": true/false, "data": ..., "error": {...}} + * Error codes map to the same ApiError enum as v1 for backward compatibility. + */ +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) { + e.printStackTrace(); + } + } + } + + return builder.build(); + } + + /** + * Build the base URL for APIv2 requests. + */ + private static String buildBaseUrl(Context context) { + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + String baseUrl = prefs.getString("ttrss_url", "").trim(); + return baseUrl + "/api/v2/"; + } + + /** + * Execute a GET request. + */ + public static JsonElement get(Context context, String path, ApiCommon.ApiCaller caller) { + return execute(context, "GET", path, null, caller, null); + } + + /** + * Execute a GET request with query parameters. + */ + public static JsonElement get(Context context, String path, Map<String, String> queryParams, ApiCommon.ApiCaller caller) { + return execute(context, "GET", path, null, caller, queryParams); + } + + /** + * Execute a POST request with form-encoded body. + */ + public static JsonElement postForm(Context context, String path, Map<String, String> bodyParams, ApiCommon.ApiCaller caller) { + return execute(context, "POST", path, bodyParams, caller, null); + } + + /** + * Execute a POST request with JSON body. + */ + public static JsonElement postJson(Context context, String path, Map<String, String> bodyParams, ApiCommon.ApiCaller caller) { + return execute(context, "POST", path, bodyParams, caller, null); + } + + /** + * Execute a PATCH request with form-encoded body. + */ + public static JsonElement patchForm(Context context, String path, Map<String, String> bodyParams, ApiCommon.ApiCaller caller) { + return execute(context, "PATCH", path, bodyParams, caller, null); + } + + /** + * Execute a DELETE request. + */ + public static JsonElement delete(Context context, String path, ApiCommon.ApiCaller caller) { + return execute(context, "DELETE", path, null, caller, null); + } + + /** + * Execute a DELETE request with form-encoded body. + */ + public static JsonElement deleteForm(Context context, String path, Map<String, String> bodyParams, ApiCommon.ApiCaller caller) { + return execute(context, "DELETE", path, bodyParams, caller, null); + } + + // ─── Core request execution ─────────────────────────────────────────────── + + private static JsonElement execute(Context context, String method, String path, + Map<String, String> bodyParams, + ApiCommon.ApiCaller caller, + Map<String, String> queryParams) { + try { + if (!ApiCommon.isNetworkAvailable(context)) { + caller.setLastError(ApiError.NETWORK_UNAVAILABLE); + return null; + } + + String baseUrl = buildBaseUrl(context); + String fullUrl = baseUrl + path; + + // Build query string + if (queryParams != null && !queryParams.isEmpty()) { + HttpUrl.Builder urlBuilder = HttpUrl.parse(fullUrl).newBuilder(); + for (Map.Entry<String, String> entry : queryParams.entrySet()) { + urlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); + } + fullUrl = urlBuilder.build().toString(); + } + + // Build request body (for POST/PATCH/DELETE with body params) + RequestBody requestBody = null; + if (bodyParams != null && !bodyParams.isEmpty()) { + // Use form-encoded body for v2 API + FormBody.Builder formBuilder = new FormBody.Builder(); + for (Map.Entry<String, String> entry : bodyParams.entrySet()) { + formBuilder.add(entry.getKey(), entry.getValue() != null ? entry.getValue() : ""); + } + requestBody = formBuilder.build(); + } + + // Build request + Request.Builder requestBuilder = new Request.Builder() + .url(fullUrl) + .header("User-Agent", getUserAgent(context)); + + // Add session header for authenticated endpoints + String sessionId = org.fox.ttrss.Application.getInstance().getSessionId(); + if (sessionId != null && !sessionId.isEmpty()) { + requestBuilder.header("X-Session-ID", sessionId); + } + + // Add HTTP Basic auth if configured + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + String httpLogin = prefs.getString("http_login", "").trim(); + String httpPassword = prefs.getString("http_password", "").trim(); + if (!httpLogin.isEmpty()) { + requestBuilder.header("Authorization", Credentials.basic(httpLogin, httpPassword)); + } + + // Set HTTP method and body + if (requestBody != null) { + requestBuilder.method(method, requestBody); + } else { + requestBuilder.method(method, null); + } + + // Debug logging + SharedPreferences prefsDebug = PreferenceManager.getDefaultSharedPreferences(context); + if (prefsDebug.getBoolean("transport_debugging", false)) { + Log.d(TAG, ">>> " + method + " " + fullUrl); + if (bodyParams != null && !bodyParams.isEmpty()) { + Log.d(TAG, " body: " + new Gson().toJson(bodyParams)); + } + } + + // Build client and execute + OkHttpClient client = buildClient(context, null); + Response response = client.newCall(requestBuilder.build()).execute(); + + if (response.isSuccessful()) { + String payload = response.body().string(); + + if (prefsDebug.getBoolean("transport_debugging", false)) { + Log.d(TAG, "<<< " + payload); + } + + return parseV2Response(payload, caller); + } else { + // Handle HTTP error codes + response.body().close(); + mapHttpStatusError(response.code(), caller); + return null; + } + + } catch (javax.net.ssl.SSLPeerUnverifiedException e) { + caller.setLastError(ApiError.SSL_REJECTED); + caller.setLastErrorMessage(e.getMessage()); + e.printStackTrace(); + return null; + } catch (IOException e) { + caller.setLastError(ApiError.IO_ERROR); + caller.setLastErrorMessage(e.getMessage()); + + if (e.getMessage() != null && e.getMessage().matches("Hostname [^ ]+ was not verified")) { + caller.setLastError(ApiError.SSL_HOSTNAME_REJECTED); + } + + e.printStackTrace(); + return null; + } catch (Exception e) { + caller.setLastError(ApiError.OTHER_ERROR); + caller.setLastErrorMessage(e.getMessage()); + e.printStackTrace(); + return null; + } + } + + /** + * Parse the v2 response wrapper: {"success": true/false, "data": ..., "error": {...}} + */ + private static JsonElement parseV2Response(String payload, ApiCommon.ApiCaller caller) { + JsonParser parser = new JsonParser(); + JsonElement result = parser.parse(payload); + + try { + JsonObject resultObj = result.getAsJsonObject(); + boolean success = resultObj.get("success").getAsBoolean(); + + if (success) { + caller.setLastError(ApiError.SUCCESS); + JsonElement data = resultObj.get("data"); + return data != null ? data : JsonParser.parseString("null"); + } else { + // Error response + JsonObject errorObj = resultObj.getAsJsonObject("error"); + String errorCode = errorObj != null && errorObj.has("code") + ? errorObj.get("code").getAsString() + : "UNKNOWN"; + + mapApiError(errorCode, caller); + return null; + } + } catch (Exception e) { + caller.setLastError(ApiError.PARSE_ERROR); + caller.setLastErrorMessage("Failed to parse v2 response: " + e.getMessage()); + e.printStackTrace(); + return null; + } + } + + /** + * Map v2 error codes to the common ApiError enum. + */ + private static void mapApiError(String errorCode, ApiCommon.ApiCaller caller) { + switch (errorCode) { + case "LOGIN_ERROR": + case "NOT_LOGGED_IN": + caller.setLastError(ApiError.LOGIN_FAILED); + break; + case "API_DISABLED": + caller.setLastError(ApiError.API_DISABLED); + break; + case "INCORRECT_USAGE": + caller.setLastError(ApiError.API_INCORRECT_USAGE); + break; + default: + Log.d(TAG, "Unknown APIv2 error: " + errorCode); + caller.setLastErrorMessage(errorCode); + caller.setLastError(ApiError.API_UNKNOWN); + break; + } + } + + /** + * Map HTTP status codes to the common ApiError enum. + */ + private static void mapHttpStatusError(int httpCode, ApiCommon.ApiCaller caller) { + switch (httpCode) { + case 400: + caller.setLastError(ApiError.HTTP_BAD_REQUEST); + break; + case 401: + caller.setLastError(ApiError.HTTP_UNAUTHORIZED); + break; + case 403: + caller.setLastError(ApiError.HTTP_FORBIDDEN); + break; + case 404: + caller.setLastError(ApiError.HTTP_NOT_FOUND); + break; + case 405: + // @todo what about METHOD_NOT_ALLOWED? do these two share status code? + caller.setLastError(ApiError.API_UNKNOWN_METHOD); + break; + case 500: + case 501: + caller.setLastError(ApiError.HTTP_SERVER_ERROR); + break; + default: + Log.d(TAG, "HTTP error code: " + httpCode); + caller.setLastErrorMessage("HTTP " + httpCode); + caller.setLastError(ApiError.HTTP_OTHER_ERROR); + break; + } + } + + // ─── 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 ────────────────────────────────────────────────────────────── + + private static String getUserAgent(Context context) { + try { + PackageInfo packageInfo = context.getPackageManager() + .getPackageInfo(context.getPackageName(), 0); + + return String.format(Locale.ENGLISH, + "Tiny Tiny RSS (Android) %1$s (%2$d) %3$s", + packageInfo.versionName, + packageInfo.versionCode, + System.getProperty("http.agent")); + + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + return String.format(Locale.ENGLISH, + "Tiny Tiny RSS (Android) Unknown %1$s", + System.getProperty("http.agent")); + } + } +} diff --git a/org.fox.ttrss/src/main/java/org/fox/ttrss/ArticleModel.java b/org.fox.ttrss/src/main/java/org/fox/ttrss/ArticleModel.java index 66431082..7e1189cd 100644 --- a/org.fox.ttrss/src/main/java/org/fox/ttrss/ArticleModel.java +++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/ArticleModel.java @@ -389,7 +389,7 @@ public class ArticleModel extends AndroidViewModel implements ApiCommon.ApiCalle return ApiCommon.getErrorMessage(m_lastError); } - ApiCommon.ApiError getLastError() { + public ApiCommon.ApiError getLastError() { return m_lastError; } diff --git a/org.fox.ttrss/src/main/java/org/fox/ttrss/FeedsModel.java b/org.fox.ttrss/src/main/java/org/fox/ttrss/FeedsModel.java index c6c68281..ff3510ad 100644 --- a/org.fox.ttrss/src/main/java/org/fox/ttrss/FeedsModel.java +++ b/org.fox.ttrss/src/main/java/org/fox/ttrss/FeedsModel.java @@ -160,7 +160,7 @@ public class FeedsModel extends AndroidViewModel implements ApiCommon.ApiCaller return ApiCommon.getErrorMessage(m_lastError); } - ApiCommon.ApiError getLastError() { + public ApiCommon.ApiError getLastError() { return m_lastError; } |
