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.content.res.Resources;
21 import android.os.AsyncTask;
22 import android.util.Log;
23 import android.util.SparseArray;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.fasterxml.jackson.databind.ObjectWriter;
28 import net.ktnx.mobileledger.R;
29 import net.ktnx.mobileledger.model.LedgerTransaction;
30 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
31 import net.ktnx.mobileledger.model.MobileLedgerProfile;
32 import net.ktnx.mobileledger.utils.Globals;
33 import net.ktnx.mobileledger.utils.Logger;
34 import net.ktnx.mobileledger.utils.NetworkUtil;
35 import net.ktnx.mobileledger.utils.SimpleDate;
36 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
38 import java.io.BufferedReader;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.io.OutputStream;
43 import java.net.HttpURLConnection;
44 import java.nio.charset.StandardCharsets;
45 import java.util.List;
46 import java.util.Locale;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
51 import static android.os.SystemClock.sleep;
52 import static net.ktnx.mobileledger.utils.Logger.debug;
54 /* TODO: get rid of the custom session/cookie and auth code?
55 * (the last problem with the POST was the missing content-length header)
56 * This will resolve itself when hledger-web 1.14+ is released with Debian/stable,
57 * at which point the HTML form emulation can be dropped entirely
60 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
61 private final TaskCallback taskCallback;
62 private final MobileLedgerProfile mProfile;
63 private final boolean simulate;
64 protected String error;
66 private String session;
67 private LedgerTransaction transaction;
69 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
71 taskCallback = callback;
73 this.simulate = simulate;
75 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
76 taskCallback = callback;
80 private boolean send_1_15_OK() throws IOException {
81 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
82 http.setRequestMethod("PUT");
83 http.setRequestProperty("Content-Type", "application/json");
84 http.setRequestProperty("Accept", "*/*");
86 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction jsonTransaction =
87 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.fromLedgerTransaction(
89 ObjectMapper mapper = new ObjectMapper();
91 mapper.writerFor(net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.class);
92 String body = writer.writeValueAsString(jsonTransaction);
94 return sendRequest(http, body);
96 private boolean send_1_14_OK() throws IOException {
97 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
98 http.setRequestMethod("PUT");
99 http.setRequestProperty("Content-Type", "application/json");
100 http.setRequestProperty("Accept", "*/*");
102 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction jsonTransaction =
103 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.fromLedgerTransaction(
105 ObjectMapper mapper = new ObjectMapper();
106 ObjectWriter writer =
107 mapper.writerFor(net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.class);
108 String body = writer.writeValueAsString(jsonTransaction);
110 return sendRequest(http, body);
112 private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
114 debug("network", "The request would be: " + body);
117 if (Math.random() > 0.3)
118 throw new RuntimeException("Simulated test exception");
120 catch (InterruptedException ex) {
121 Logger.debug("network", ex.toString());
127 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
128 http.setDoOutput(true);
129 http.setDoInput(true);
130 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
132 debug("network", "request header: " + http.getRequestProperties()
135 try (OutputStream req = http.getOutputStream()) {
136 debug("network", "Request body: " + body);
137 req.write(bodyBytes);
139 final int responseCode = http.getResponseCode();
140 debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
141 http.getResponseMessage()));
143 try (InputStream resp = http.getErrorStream()) {
145 switch (responseCode) {
151 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
155 line = reader.readLine();
158 Logger.debug("network", line);
161 return false; // will cause a retry with the legacy method
164 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
165 String line = reader.readLine();
166 debug("network", "Response content: " + line);
167 throw new IOException(
168 String.format("Error response code %d", responseCode));
175 private boolean legacySendOK() throws IOException {
176 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
177 http.setRequestMethod("POST");
178 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
179 http.setRequestProperty("Accept", "*/*");
180 if ((session != null) && !session.isEmpty()) {
181 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
183 http.setDoOutput(true);
184 http.setDoInput(true);
186 UrlEncodedFormData params = new UrlEncodedFormData();
187 params.addPair("_formid", "identify-add");
189 params.addPair("_token", token);
191 SimpleDate transactionDate = transaction.getDateIfAny();
192 if (transactionDate == null)
193 transactionDate = SimpleDate.today();
195 params.addPair("date", Globals.formatLedgerDate(transactionDate));
196 params.addPair("description", transaction.getDescription());
197 for (LedgerTransactionAccount acc : transaction.getAccounts()) {
198 params.addPair("account", acc.getAccountName());
199 if (acc.isAmountSet())
200 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
202 params.addPair("amount", "");
205 String body = params.toString();
206 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
208 debug("network", "request header: " + http.getRequestProperties()
211 try (OutputStream req = http.getOutputStream()) {
212 debug("network", "Request body: " + body);
213 req.write(body.getBytes(StandardCharsets.US_ASCII));
215 try (InputStream resp = http.getInputStream()) {
216 debug("update_accounts", String.valueOf(http.getResponseCode()));
217 if (http.getResponseCode() == 303) {
218 // everything is fine
221 else if (http.getResponseCode() == 200) {
222 // get the new cookie
224 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
226 Map<String, List<String>> header = http.getHeaderFields();
227 List<String> cookieHeader = header.get("Set-Cookie");
228 if (cookieHeader != null) {
229 String cookie = cookieHeader.get(0);
230 Matcher m = reSessionCookie.matcher(cookie);
232 session = m.group(1);
233 debug("network", "new session is " + session);
236 debug("network", "set-cookie: " + cookie);
238 "Response Set-Cookie headers is not a _SESSION one");
242 Log.w("network", "Response has no Set-Cookie header");
245 // the token needs to be updated
246 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
247 Pattern re = Pattern.compile(
248 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
250 while ((line = reader.readLine()) != null) {
251 //debug("dump", line);
252 Matcher m = re.matcher(line);
255 debug("save-transaction", line);
256 debug("save-transaction", "Token=" + token);
257 return false; // retry
260 throw new IOException("Can't find _token string");
263 throw new IOException(
264 String.format("Error response code %d", http.getResponseCode()));
270 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
273 transaction = ledgerTransactions[0];
275 switch (mProfile.getApiVersion()) {
277 Logger.debug("network", "Trying version 1.5.");
278 if (!send_1_15_OK()) {
279 Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
280 if (!send_1_14_OK()) {
281 Logger.debug("network",
282 "Version 1.14 failed too. Trying HTML form emulation");
283 legacySendOkWithRetry();
286 Logger.debug("network", "Version 1.14 request succeeded");
290 Logger.debug("network", "Version 1.15 request succeeded");
294 legacySendOkWithRetry();
303 throw new IllegalStateException(
304 "Unexpected API version: " + mProfile.getApiVersion());
307 catch (Exception e) {
309 error = e.getMessage();
314 private void legacySendOkWithRetry() throws IOException {
316 while (!legacySendOK()) {
319 throw new IOException(String.format("aborting after %d tries", tried));
324 protected void onPostExecute(Void aVoid) {
325 super.onPostExecute(aVoid);
326 taskCallback.done(error);
330 auto(0), html(-1), v1_14(-2), v1_15(-3), v1_19_1(-4);
331 private static final SparseArray<API> map = new SparseArray<>();
332 public static API[] allVersions = {v1_19_1, v1_15, v1_14};
335 for (API item : API.values()) {
336 map.put(item.value, item);
340 private final int value;
345 public static API valueOf(int i) {
346 return map.get(i, auto);
351 public String getDescription(Resources resources) {
354 return resources.getString(R.string.api_auto);
356 return resources.getString(R.string.api_html);
358 return resources.getString(R.string.api_1_14);
360 return resources.getString(R.string.api_1_15);
362 return resources.getString(R.string.api_1_19_1);
364 throw new IllegalStateException("Unexpected value: " + value);
367 public String getDescription() {
370 return "(automatic)";
380 throw new IllegalStateException("Unexpected value: " + this);