about summary refs log tree commit diff stats
path: root/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiV2Client.java
blob: 73c694298a6e7b348c993204b16f83b7e7eea052 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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<String, Object> 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, Object> 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, Object> 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, Object> 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, Object> bodyParams,
                                       ApiCommon.ApiCaller caller,
                                       Map<String, Object> 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<String, Object> 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<String, Object> 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"));
        }
    }
}