2 * Copyright © 2023 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.async;
20 import static net.ktnx.mobileledger.utils.Logger.debug;
22 import android.util.Log;
24 import net.ktnx.mobileledger.db.Profile;
25 import net.ktnx.mobileledger.json.API;
26 import net.ktnx.mobileledger.json.ApiNotSupportedException;
27 import net.ktnx.mobileledger.json.Gateway;
28 import net.ktnx.mobileledger.model.LedgerTransaction;
29 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
30 import net.ktnx.mobileledger.utils.Globals;
31 import net.ktnx.mobileledger.utils.Logger;
32 import net.ktnx.mobileledger.utils.Misc;
33 import net.ktnx.mobileledger.utils.NetworkUtil;
34 import net.ktnx.mobileledger.utils.SimpleDate;
35 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
37 import java.io.BufferedReader;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.io.OutputStream;
42 import java.net.HttpURLConnection;
43 import java.nio.charset.StandardCharsets;
44 import java.util.List;
45 import java.util.Locale;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
50 /* TODO: get rid of the custom session/cookie and auth code?
51 * (the last problem with the POST was the missing content-length header)
52 * This will resolve itself when hledger-web 1.14+ is released with Debian/stable,
53 * at which point the HTML form emulation can be dropped entirely
56 public class SendTransactionTask extends Thread {
57 private final TaskCallback taskCallback;
58 private final Profile mProfile;
59 private final boolean simulate;
60 private final LedgerTransaction transaction;
61 protected String error;
63 private String session;
65 public SendTransactionTask(TaskCallback callback, Profile profile,
66 LedgerTransaction transaction, boolean simulate) {
67 taskCallback = callback;
69 this.transaction = transaction;
70 this.simulate = simulate;
72 private void sendOK(API apiVersion) throws IOException, ApiNotSupportedException {
73 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
74 http.setRequestMethod("PUT");
75 http.setRequestProperty("Content-Type", "application/json");
76 http.setRequestProperty("Accept", "*/*");
78 Gateway gateway = Gateway.forApiVersion(apiVersion);
79 String body = gateway.transactionSaveRequest(transaction);
81 Logger.debug("network", "Sending using API " + apiVersion);
82 sendRequest(http, body);
84 private void sendRequest(HttpURLConnection http, String body)
85 throws IOException, ApiNotSupportedException {
87 debug("network", "The request would be: " + body);
90 if (Math.random() > 0.3)
91 throw new RuntimeException("Simulated test exception");
93 catch (InterruptedException ex) {
94 Logger.debug("network", ex.toString());
100 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
101 http.setDoOutput(true);
102 http.setDoInput(true);
103 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
105 debug("network", "request header: " + http.getRequestProperties()
108 try (OutputStream req = http.getOutputStream()) {
109 debug("network", "Request body: " + body);
110 req.write(bodyBytes);
112 final int responseCode = http.getResponseCode();
113 debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
114 http.getResponseMessage()));
116 try (InputStream resp = http.getErrorStream()) {
118 switch (responseCode) {
124 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
125 StringBuilder errorLines = new StringBuilder();
128 String line = reader.readLine();
131 Logger.debug("network", line);
133 if (errorLines.length() != 0)
134 errorLines.append("\n");
136 errorLines.append(line);
139 throw new ApiNotSupportedException(errorLines.toString());
142 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
143 String line = reader.readLine();
144 debug("network", "Response content: " + line);
145 throw new IOException(
146 String.format("Error response code %d", responseCode));
151 private boolean legacySendOK() throws IOException {
152 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
153 http.setRequestMethod("POST");
154 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
155 http.setRequestProperty("Accept", "*/*");
156 if ((session != null) && !session.isEmpty()) {
157 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
159 http.setDoOutput(true);
160 http.setDoInput(true);
162 UrlEncodedFormData params = new UrlEncodedFormData();
163 params.addPair("_formid", "identify-add");
165 params.addPair("_token", token);
167 SimpleDate transactionDate = transaction.getDateIfAny();
168 if (transactionDate == null)
169 transactionDate = SimpleDate.today();
171 params.addPair("date", Globals.formatLedgerDate(transactionDate));
172 params.addPair("description", transaction.getDescription());
173 for (LedgerTransactionAccount acc : transaction.getAccounts()) {
174 params.addPair("account", acc.getAccountName());
175 if (acc.isAmountSet())
176 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
178 params.addPair("amount", "");
181 String body = params.toString();
182 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
184 debug("network", "request header: " + http.getRequestProperties()
187 try (OutputStream req = http.getOutputStream()) {
188 debug("network", "Request body: " + body);
189 req.write(body.getBytes(StandardCharsets.US_ASCII));
191 try (InputStream resp = http.getInputStream()) {
192 debug("update_accounts", String.valueOf(http.getResponseCode()));
193 if (http.getResponseCode() == 303) {
194 // everything is fine
197 else if (http.getResponseCode() == 200) {
198 // get the new cookie
200 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
202 Map<String, List<String>> header = http.getHeaderFields();
203 List<String> cookieHeader = header.get("Set-Cookie");
204 if (cookieHeader != null) {
205 String cookie = cookieHeader.get(0);
206 Matcher m = reSessionCookie.matcher(cookie);
208 session = m.group(1);
209 debug("network", "new session is " + session);
212 debug("network", "set-cookie: " + cookie);
214 "Response Set-Cookie headers is not a _SESSION one");
218 Log.w("network", "Response has no Set-Cookie header");
221 // the token needs to be updated
222 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
223 Pattern re = Pattern.compile(
224 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
226 while ((line = reader.readLine()) != null) {
227 //debug("dump", line);
228 Matcher m = re.matcher(line);
231 debug("save-transaction", line);
232 debug("save-transaction", "Token=" + token);
233 return false; // retry
236 throw new IOException("Can't find _token string");
239 throw new IOException(
240 String.format("Error response code %d", http.getResponseCode()));
249 final API profileApiVersion = API.valueOf(mProfile.getApiVersion());
250 switch (profileApiVersion) {
252 boolean sendOK = false;
253 for (API ver : API.allVersions) {
254 Logger.debug("network", "Trying version " + ver);
258 Logger.debug("network", "Version " + ver + " request succeeded");
262 catch (ApiNotSupportedException e) {
263 Logger.debug("network", "Version " + ver + " seems not supported");
268 Logger.debug("network", "Trying HTML form emulation");
269 legacySendOkWithRetry();
273 legacySendOkWithRetry();
279 sendOK(profileApiVersion);
282 throw new IllegalStateException("Unexpected API version: " + profileApiVersion);
285 catch (ApiNotSupportedException | Exception e) {
287 error = e.getMessage();
290 Misc.onMainThread(() -> taskCallback.onTransactionSaveDone(error, transaction));
292 private void legacySendOkWithRetry() throws IOException {
294 while (!legacySendOK()) {
297 throw new IOException(String.format("aborting after %d tries", tried));
301 catch (InterruptedException e) {