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 org.fox.ttrss.ApiCommon.ApiError; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.Map; import okhttp3.Credentials; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * 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 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 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 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 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 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 bodyParams, ApiCommon.ApiCaller caller, Map 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()) { // This uses different notation in V1 api so we can't remove those at the source just yet and keep // compatibility, for now just drop them here (our route should be specified with URL path) queryParams.remove("op"); queryParams.remove("method"); // no arrays for query params HttpUrl.Builder urlBuilder = HttpUrl.parse(fullUrl).newBuilder(); for (Map.Entry entry : queryParams.entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); } fullUrl = urlBuilder.build().toString(); } // Build request body (for POST/PATCH/DELETE with body params) RequestBody requestBody = null; if (bodyParams != null && !bodyParams.isEmpty()) { // This uses different notation in V1 api so we can't remove those at the source just yet and keep // compatibility, for now just drop them here (our route should be specified with URL path) bodyParams.remove("op"); bodyParams.remove("method"); // Use form-encoded body for v2 API FormBody.Builder formBuilder = new FormBody.Builder(); for (Map.Entry entry : bodyParams.entrySet()) { Object value = entry.getValue(); if (value instanceof List) { // Handle Java Lists (like ArrayList) List list = (List) value; for (Object item : list) { formBuilder.add(entry.getKey() + "[]", item != null ? item.toString() : ""); } } else if (value.getClass().isArray()) { // Handle standard Java Arrays (like String[]) int length = java.lang.reflect.Array.getLength(value); for (int i = 0; i < length; i++) { Object item = java.lang.reflect.Array.get(value, i); formBuilder.add(entry.getKey() + "[]", item != null ? item.toString() : ""); } } else { // Handle primitive types (String, Integer, Boolean) formBuilder.add(entry.getKey(), value.toString()); } } 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 = OkHttpFactory.createClient(context, null, 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); } ApiResponseParser.ParsedResponse parsed = ApiResponseParser.parse(payload); caller.setLastError(parsed.error); caller.setLastErrorMessage(parsed.errorMessage); return parsed.data; } else { // Handle HTTP error codes response.body().close(); ApiError error = ApiResponseParser.mapHttpStatusError(response.code()); caller.setLastError(error); caller.setLastErrorMessage("HTTP " + response.code()); return null; } } catch (javax.net.ssl.SSLPeerUnverifiedException e) { caller.setLastError(ApiError.SSL_REJECTED); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); Log.e(TAG, "API response error", e); return null; } catch (IOException e) { caller.setLastError(ApiError.IO_ERROR); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); if (e.getMessage() != null && e.getMessage().matches("Hostname [^ ]+ was not verified")) { caller.setLastError(ApiError.SSL_HOSTNAME_REJECTED); } Log.e(TAG, "SSL peer unverified", e); return null; } catch (Exception e) { caller.setLastError(ApiError.OTHER_ERROR); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); Log.e(TAG, "IO error during request", e); return null; } } // ─── 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) { Log.e(TAG, "unexpected error", e); return String.format(Locale.ENGLISH, "Tiny Tiny RSS (Android) Unknown %1$s", System.getProperty("http.agent")); } } }