package org.fox.ttrss; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.AssetFileDescriptor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import androidx.annotation.NonNull; 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 java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import okhttp3.Credentials; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; 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; private static final MediaType TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); public interface ApiCaller { void setStatusCode(int statusCode); void setLastError(ApiError lastError); void setLastErrorMessage(String message); void setLastException(Throwable e); void notifyProgress(int progress); ApiError getLastError(); Throwable getLastException(); } public enum ApiError { SUCCESS, UNKNOWN_ERROR, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_BAD_REQUEST, HTTP_SERVER_ERROR, HTTP_OTHER_ERROR, SSL_REJECTED, SSL_HOSTNAME_REJECTED, PARSE_ERROR, IO_ERROR, OTHER_ERROR, API_DISABLED, API_UNKNOWN, LOGIN_FAILED, INVALID_URL, API_INCORRECT_USAGE, NETWORK_UNAVAILABLE, API_UNKNOWN_METHOD } public static int getErrorMessage(ApiError error) { switch (error) { case SUCCESS: return R.string.error_success; case UNKNOWN_ERROR: return R.string.error_unknown; case HTTP_UNAUTHORIZED: return R.string.error_http_unauthorized; case HTTP_BAD_REQUEST: return R.string.error_bad_request; case HTTP_FORBIDDEN: return R.string.error_http_forbidden; case HTTP_NOT_FOUND: return R.string.error_http_not_found; case HTTP_SERVER_ERROR: return R.string.error_http_server_error; case HTTP_OTHER_ERROR: return R.string.error_http_other_error; case SSL_REJECTED: return R.string.error_ssl_rejected; case SSL_HOSTNAME_REJECTED: return R.string.error_ssl_hostname_rejected; case PARSE_ERROR: return R.string.error_parse_error; case IO_ERROR: return R.string.error_io_error; case OTHER_ERROR: return R.string.error_other_error; case API_DISABLED: return R.string.error_api_disabled; case API_UNKNOWN: return R.string.error_api_unknown; case API_UNKNOWN_METHOD: return R.string.error_api_unknown_method; case LOGIN_FAILED: return R.string.error_login_failed; case INVALID_URL: return R.string.error_invalid_api_url; case API_INCORRECT_USAGE: return R.string.error_api_incorrect_usage; case NETWORK_UNAVAILABLE: return R.string.error_network_unavailable; default: Log.d(TAG, "getErrorMessage: unknown error code=" + error); return R.string.error_unknown; } } static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null // otherwise check if we are connected 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 params, @NonNull ApiCommon.ApiCaller caller) { String op = (String) params.get("op"); if (op == null) { caller.setLastError(ApiError.API_UNKNOWN_METHOD); return null; } Map queryParams = new HashMap<>(); Map bodyParams = new HashMap<>(); // Separate sid from params (v2 uses X-Session-ID header instead) 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 = (String) bodyParams.get("feed_id"); return ApiV2Client.delete(context, "feeds/" + feedId, caller); case "updateFeed": String uid = (String) 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); // skip gets replaced with offset in api v2 queryParams.remove("skip"); queryParams.put("offset", bodyParams.get("skip")); bodyParams.clear(); return ApiV2Client.get(context, "articles", queryParams, caller); case "getArticle": String articleIds = (String) 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 v2BatchBody = new HashMap<>(); String articleIdsParam = (String) bodyParams.get("article_ids"); if (articleIdsParam != null) { // Convert CSV to JSON array string for v2 String[] ids = articleIdsParam.split(","); v2BatchBody.put("ids", ids); } String fieldStr = (String) bodyParams.get("field"); String modeStr = (String) bodyParams.get("mode"); if (fieldStr != null && modeStr != null) { int field, mode; try { field = Integer.parseInt(fieldStr); mode = Integer.parseInt(modeStr); } catch (NumberFormatException e) { Log.d(TAG, "Invalid field/mode values: field=" + fieldStr + " mode=" + modeStr); return null; } 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 = (String) 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 = (String) bodyParams.get("label_id"); String assign = (String) bodyParams.get("assign"); if (labelId == null) { caller.setLastError(ApiError.API_INCORRECT_USAGE); return null; } Map labelBody = new HashMap<>(); // Convert CSV to JSON array String articleIdsLbl = (String) bodyParams.get("article_ids"); if (articleIdsLbl != null) { String[] ids = articleIdsLbl.split(","); labelBody.put("article_ids", ids); } if ("true".equals(assign)) { 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 = (String) 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 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, 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); return null; } SharedPreferences m_prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean m_transportDebugging = m_prefs.getBoolean("transport_debugging", false); Gson gson = new Gson(); String payload = gson.toJson(new HashMap<>(params)); String apiUrl = m_prefs.getString("ttrss_url", "").trim() + "/api/"; if (m_transportDebugging) Log.d(TAG, ">>> " + payload + " -> " + apiUrl); Request.Builder requestBuilder = new Request.Builder() .url(apiUrl) .header("User-Agent", getUserAgent(context)) .post(RequestBody.create(TYPE_JSON, payload)); String httpLogin = m_prefs.getString("http_login", "").trim(); String httpPassword = m_prefs.getString("http_password", "").trim(); if (!httpLogin.isEmpty()) { if (m_transportDebugging) Log.d(TAG, "Using HTTP Basic authentication."); requestBuilder.addHeader("Authorization", Credentials.basic(httpLogin, httpPassword)); } Request request = requestBuilder.build(); OkHttpFactory.ProgressListener listener = (url, bytesRead, contentLength) -> { // Log.d(TAG, "[progress] " + url + " " + bytesRead + " of " + contentLength); if (contentLength > 0) caller.notifyProgress((int) (bytesRead * 100f / contentLength)); }; OkHttpClient client = OkHttpFactory.createClient(context, listener, caller); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { String payloadReceived = response.body().string(); if (m_transportDebugging) Log.d(TAG, "<<< " + payloadReceived); JsonParser parser = new JsonParser(); JsonElement result = parser.parse(payloadReceived); JsonObject resultObj = result.getAsJsonObject(); int statusCode = resultObj.get("status").getAsInt(); caller.setStatusCode(statusCode); switch (statusCode) { case API_STATUS_OK: caller.setLastError(ApiError.SUCCESS); return result.getAsJsonObject().get("content"); case API_STATUS_ERR: JsonObject contentObj = resultObj.get("content").getAsJsonObject(); String error = contentObj.get("error").getAsString(); switch (error) { 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; case "UNKNOWN_METHOD": caller.setLastError(ApiError.API_UNKNOWN_METHOD); break; default: Log.d(TAG, "Unknown API error: " + error); caller.setLastErrorMessage(error); caller.setLastError(ApiError.API_UNKNOWN); break; } } } else { switch (response.code()) { 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 500: case 501: caller.setLastError(ApiError.HTTP_SERVER_ERROR); break; default: Log.d(TAG, "HTTP response code: " + response.code()); caller.setLastErrorMessage("HTTP response code: " + response.code()); caller.setLastError(ApiError.HTTP_OTHER_ERROR); break; } } return null; } } catch (javax.net.ssl.SSLPeerUnverifiedException e) { caller.setLastError(ApiError.SSL_REJECTED); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); Log.e(TAG, "SSL certificate rejected", e); } catch (IOException e) { caller.setLastError(ApiError.IO_ERROR); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); if (e.getMessage() != null) { if (e.getMessage().matches("Hostname [^ ]+ was not verified")) { caller.setLastError(ApiError.SSL_HOSTNAME_REJECTED); } } Log.e(TAG, "IO error", e); } catch (com.google.gson.JsonSyntaxException e) { caller.setLastError(ApiError.PARSE_ERROR); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); Log.e(TAG, "JSON parse error", e); } catch (Exception e) { caller.setLastError(ApiError.OTHER_ERROR); caller.setLastErrorMessage(e.getMessage()); caller.setLastException(e); Log.e(TAG, "API request failed", e); } return null; } 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, "getting package info", e); return String.format(Locale.ENGLISH, "Tiny Tiny RSS (Android) Unknown %1$s", System.getProperty("http.agent")); } } }