2 * Copyright © 2020 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 android.os.AsyncTask;
21 import android.util.Log;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.ObjectWriter;
26 import net.ktnx.mobileledger.model.LedgerTransaction;
27 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
28 import net.ktnx.mobileledger.model.MobileLedgerProfile;
29 import net.ktnx.mobileledger.utils.Globals;
30 import net.ktnx.mobileledger.utils.Logger;
31 import net.ktnx.mobileledger.utils.NetworkUtil;
32 import net.ktnx.mobileledger.utils.SimpleDate;
33 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
35 import java.io.BufferedReader;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.InputStreamReader;
39 import java.io.OutputStream;
40 import java.net.HttpURLConnection;
41 import java.nio.charset.StandardCharsets;
42 import java.util.List;
43 import java.util.Locale;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
48 import static android.os.SystemClock.sleep;
49 import static net.ktnx.mobileledger.utils.Logger.debug;
51 /* TODO: get rid of the custom session/cookie and auth code?
52 * (the last problem with the POST was the missing content-length header)
53 * This will resolve itself when hledger-web 1.14+ is released with Debian/stable,
54 * at which point the HTML form emulation can be dropped entirely
57 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
58 private final TaskCallback taskCallback;
59 private final MobileLedgerProfile mProfile;
60 private final boolean simulate;
61 protected String error;
63 private String session;
64 private LedgerTransaction transaction;
66 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
68 taskCallback = callback;
70 this.simulate = simulate;
72 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
73 taskCallback = callback;
77 private boolean send_1_15_OK() throws IOException {
78 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
79 http.setRequestMethod("PUT");
80 http.setRequestProperty("Content-Type", "application/json");
81 http.setRequestProperty("Accept", "*/*");
83 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction jsonTransaction =
84 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.fromLedgerTransaction(
86 ObjectMapper mapper = new ObjectMapper();
88 mapper.writerFor(net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.class);
89 String body = writer.writeValueAsString(jsonTransaction);
91 return sendRequest(http, body);
93 private boolean send_1_14_OK() throws IOException {
94 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
95 http.setRequestMethod("PUT");
96 http.setRequestProperty("Content-Type", "application/json");
97 http.setRequestProperty("Accept", "*/*");
99 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction jsonTransaction =
100 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.fromLedgerTransaction(
102 ObjectMapper mapper = new ObjectMapper();
103 ObjectWriter writer =
104 mapper.writerFor(net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.class);
105 String body = writer.writeValueAsString(jsonTransaction);
107 return sendRequest(http, body);
109 private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
111 debug("network", "The request would be: " + body);
114 if (Math.random() > 0.3)
115 throw new RuntimeException("Simulated test exception");
117 catch (InterruptedException ex) {
118 Logger.debug("network", ex.toString());
124 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
125 http.setDoOutput(true);
126 http.setDoInput(true);
127 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
129 debug("network", "request header: " + http.getRequestProperties()
132 try (OutputStream req = http.getOutputStream()) {
133 debug("network", "Request body: " + body);
134 req.write(bodyBytes);
136 final int responseCode = http.getResponseCode();
137 debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
138 http.getResponseMessage()));
140 try (InputStream resp = http.getErrorStream()) {
142 switch (responseCode) {
148 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
152 line = reader.readLine();
155 Logger.debug("network", line);
158 return false; // will cause a retry with the legacy method
161 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
162 String line = reader.readLine();
163 debug("network", "Response content: " + line);
164 throw new IOException(
165 String.format("Error response code %d", responseCode));
172 private boolean legacySendOK() throws IOException {
173 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
174 http.setRequestMethod("POST");
175 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
176 http.setRequestProperty("Accept", "*/*");
177 if ((session != null) && !session.isEmpty()) {
178 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
180 http.setDoOutput(true);
181 http.setDoInput(true);
183 UrlEncodedFormData params = new UrlEncodedFormData();
184 params.addPair("_formid", "identify-add");
186 params.addPair("_token", token);
188 SimpleDate transactionDate = transaction.getDateIfAny();
189 if (transactionDate == null)
190 transactionDate = SimpleDate.today();
192 params.addPair("date", Globals.formatLedgerDate(transactionDate));
193 params.addPair("description", transaction.getDescription());
194 for (LedgerTransactionAccount acc : transaction.getAccounts()) {
195 params.addPair("account", acc.getAccountName());
196 if (acc.isAmountSet())
197 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
199 params.addPair("amount", "");
202 String body = params.toString();
203 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
205 debug("network", "request header: " + http.getRequestProperties()
208 try (OutputStream req = http.getOutputStream()) {
209 debug("network", "Request body: " + body);
210 req.write(body.getBytes(StandardCharsets.US_ASCII));
212 try (InputStream resp = http.getInputStream()) {
213 debug("update_accounts", String.valueOf(http.getResponseCode()));
214 if (http.getResponseCode() == 303) {
215 // everything is fine
218 else if (http.getResponseCode() == 200) {
219 // get the new cookie
221 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
223 Map<String, List<String>> header = http.getHeaderFields();
224 List<String> cookieHeader = header.get("Set-Cookie");
225 if (cookieHeader != null) {
226 String cookie = cookieHeader.get(0);
227 Matcher m = reSessionCookie.matcher(cookie);
229 session = m.group(1);
230 debug("network", "new session is " + session);
233 debug("network", "set-cookie: " + cookie);
235 "Response Set-Cookie headers is not a _SESSION one");
239 Log.w("network", "Response has no Set-Cookie header");
242 // the token needs to be updated
243 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
244 Pattern re = Pattern.compile(
245 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
247 while ((line = reader.readLine()) != null) {
248 //debug("dump", line);
249 Matcher m = re.matcher(line);
252 debug("save-transaction", line);
253 debug("save-transaction", "Token=" + token);
254 return false; // retry
257 throw new IOException("Can't find _token string");
260 throw new IOException(
261 String.format("Error response code %d", http.getResponseCode()));
267 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
270 transaction = ledgerTransactions[0];
272 switch (mProfile.getApiVersion()) {
274 Logger.debug("network", "Trying version 1.5.");
275 if (!send_1_15_OK()) {
276 Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
277 if (!send_1_14_OK()) {
278 Logger.debug("network",
279 "Version 1.14 failed too. Trying HTML form emulation");
280 legacySendOkWithRetry();
283 Logger.debug("network", "Version 1.14 request succeeded");
287 Logger.debug("network", "Version 1.15 request succeeded");
291 legacySendOkWithRetry();
300 throw new IllegalStateException(
301 "Unexpected API version: " + mProfile.getApiVersion());
304 catch (Exception e) {
306 error = e.getMessage();
311 private void legacySendOkWithRetry() throws IOException {
313 while (!legacySendOK()) {
316 throw new IOException(String.format("aborting after %d tries", tried));
321 protected void onPostExecute(Void aVoid) {
322 super.onPostExecute(aVoid);
323 taskCallback.done(error);