package org.fox.ttrss; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.fox.ttrss.ApiCommon.ApiError; import java.util.Objects; /** * Parses TT-RSS API v2 responses and maps error codes to ApiError enum. * * This is a pure-logic class with no Android dependencies, making it * easy to unit test. ApiV2Client delegates to it after receiving HTTP responses. */ public final class ApiResponseParser { /** * Result of parsing a v2 API response. */ public static final class ParsedResponse { public final boolean success; public final JsonElement data; public final ApiError error; public final String errorMessage; public ParsedResponse(boolean success, JsonElement data, ApiError error, String errorMessage) { this.success = success; this.data = data; this.error = error; this.errorMessage = errorMessage; } } private ApiResponseParser() { // no instances } /** * Parse a v2 API response payload. * * Response format: {"success": true/false, "data": ..., "error": {"code": "..."}} * * @param payload raw JSON string from the HTTP response body * @return parsed response with success flag, data, and error info */ public static ParsedResponse parse(String payload) { try { JsonElement result = JsonParser.parseString(payload); JsonObject resultObj = result.getAsJsonObject(); boolean success = resultObj.get("success").getAsBoolean(); if (success) { JsonElement data = resultObj.get("data"); return new ParsedResponse( true, data != null ? data : JsonParser.parseString("null"), ApiError.SUCCESS, null ); } else { JsonObject errorObj = resultObj.getAsJsonObject("error"); String errorCode = errorObj != null && errorObj.has("code") ? errorObj.get("code").getAsString() : "UNKNOWN"; return new ParsedResponse( false, null, mapApiError(errorCode), errorCode ); } } catch (Exception e) { return new ParsedResponse( false, null, ApiError.PARSE_ERROR, "Failed to parse v2 response: " + e.getMessage() ); } } /** * Map v2 API error codes to the common ApiError enum. * * @param errorCode error code from the v2 API response * @return corresponding ApiError */ public static ApiError mapApiError(String errorCode) { switch (Objects.requireNonNull(errorCode)) { case "LOGIN_ERROR": case "NOT_LOGGED_IN": return ApiError.LOGIN_FAILED; case "API_DISABLED": return ApiError.API_DISABLED; case "INCORRECT_USAGE": return ApiError.API_INCORRECT_USAGE; default: return ApiError.API_UNKNOWN; } } /** * Map HTTP status codes to the common ApiError enum. * * @param httpCode raw HTTP response status code * @return corresponding ApiError */ public static ApiError mapHttpStatusError(int httpCode) { switch (httpCode) { case 400: return ApiError.HTTP_BAD_REQUEST; case 401: return ApiError.HTTP_UNAUTHORIZED; case 403: return ApiError.HTTP_FORBIDDEN; case 404: return ApiError.HTTP_NOT_FOUND; case 405: return ApiError.API_UNKNOWN_METHOD; case 500: case 501: return ApiError.HTTP_SERVER_ERROR; default: return ApiError.HTTP_OTHER_ERROR; } } }