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 protected String error;
64 private String session;
65 private LedgerTransaction ltr;
66 private MobileLedgerProfile mProfile;
67 private boolean simulate = false;
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(ltr);
88 ObjectMapper mapper = new ObjectMapper();
90 mapper.writerFor(net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.class);
91 String body = writer.writeValueAsString(jsonTransaction);
93 return sendRequest(http, body);
95 private boolean send_1_14_OK() throws IOException {
96 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
97 http.setRequestMethod("PUT");
98 http.setRequestProperty("Content-Type", "application/json");
99 http.setRequestProperty("Accept", "*/*");
101 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction jsonTransaction =
102 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.fromLedgerTransaction(ltr);
103 ObjectMapper mapper = new ObjectMapper();
104 ObjectWriter writer =
105 mapper.writerFor(net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.class);
106 String body = writer.writeValueAsString(jsonTransaction);
108 return sendRequest(http, body);
110 private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
112 debug("network", "The request would be: " + body);
115 if (Math.random() > 0.3)
116 throw new RuntimeException("Simulated test exception");
118 catch (InterruptedException ex) {
119 Logger.debug("network", ex.toString());
125 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
126 http.setDoOutput(true);
127 http.setDoInput(true);
128 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
130 debug("network", "request header: " + http.getRequestProperties()
133 try (OutputStream req = http.getOutputStream()) {
134 debug("network", "Request body: " + body);
135 req.write(bodyBytes);
137 final int responseCode = http.getResponseCode();
139 String.format("Response: %d %s", responseCode, http.getResponseMessage()));
141 try (InputStream resp = http.getErrorStream()) {
143 switch (responseCode) {
149 return false; // will cause a retry with the legacy method
151 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
152 String line = reader.readLine();
153 debug("network", "Response content: " + line);
154 throw new IOException(
155 String.format("Error response code %d", responseCode));
162 private boolean legacySendOK() throws IOException {
163 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
164 http.setRequestMethod("POST");
165 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
166 http.setRequestProperty("Accept", "*/*");
167 if ((session != null) && !session.isEmpty()) {
168 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
170 http.setDoOutput(true);
171 http.setDoInput(true);
173 UrlEncodedFormData params = new UrlEncodedFormData();
174 params.addPair("_formid", "identify-add");
176 params.addPair("_token", token);
178 SimpleDate transactionDate = ltr.getDate();
179 if (transactionDate == null) {
180 transactionDate = SimpleDate.today();
183 params.addPair("date", Globals.formatLedgerDate(transactionDate));
184 params.addPair("description", ltr.getDescription());
185 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
186 params.addPair("account", acc.getAccountName());
187 if (acc.isAmountSet())
188 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
190 params.addPair("amount", "");
193 String body = params.toString();
194 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
196 debug("network", "request header: " + http.getRequestProperties()
199 try (OutputStream req = http.getOutputStream()) {
200 debug("network", "Request body: " + body);
201 req.write(body.getBytes(StandardCharsets.US_ASCII));
203 try (InputStream resp = http.getInputStream()) {
204 debug("update_accounts", String.valueOf(http.getResponseCode()));
205 if (http.getResponseCode() == 303) {
206 // everything is fine
209 else if (http.getResponseCode() == 200) {
210 // get the new cookie
212 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
214 Map<String, List<String>> header = http.getHeaderFields();
215 List<String> cookieHeader = header.get("Set-Cookie");
216 if (cookieHeader != null) {
217 String cookie = cookieHeader.get(0);
218 Matcher m = reSessionCookie.matcher(cookie);
220 session = m.group(1);
221 debug("network", "new session is " + session);
224 debug("network", "set-cookie: " + cookie);
226 "Response Set-Cookie headers is not a _SESSION one");
230 Log.w("network", "Response has no Set-Cookie header");
233 // the token needs to be updated
234 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
235 Pattern re = Pattern.compile(
236 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
238 while ((line = reader.readLine()) != null) {
239 //debug("dump", line);
240 Matcher m = re.matcher(line);
243 debug("save-transaction", line);
244 debug("save-transaction", "Token=" + token);
245 return false; // retry
248 throw new IOException("Can't find _token string");
251 throw new IOException(
252 String.format("Error response code %d", http.getResponseCode()));
258 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
261 ltr = ledgerTransactions[0];
263 switch (mProfile.getApiVersion()) {
265 Logger.debug("network", "Trying version 1.5.");
266 if (!send_1_15_OK()) {
267 Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
268 if (!send_1_14_OK()) {
269 Logger.debug("network",
270 "Version 1.14 failed too. Trying HTML form emulation");
271 legacySendOkWithRetry();
274 Logger.debug("network", "Version 1.14 request succeeded");
278 Logger.debug("network", "Version 1.15 request succeeded");
282 legacySendOkWithRetry();
291 throw new IllegalStateException(
292 "Unexpected API version: " + mProfile.getApiVersion());
295 catch (Exception e) {
297 error = e.getMessage();
302 private void legacySendOkWithRetry() throws IOException {
304 while (!legacySendOK()) {
307 throw new IOException(String.format("aborting after %d tries", tried));
312 protected void onPostExecute(Void aVoid) {
313 super.onPostExecute(aVoid);
314 taskCallback.done(error);
318 auto(0), html(-1), pre_1_15(-2), post_1_14(-3);
319 private static SparseArray<API> map = new SparseArray<>();
322 for (API item : API.values()) {
323 map.put(item.value, item);
332 public static API valueOf(int i) {
333 return map.get(i, auto);
338 public String getDescription(Resources resources) {
341 return resources.getString(R.string.api_auto);
343 return resources.getString(R.string.api_html);
345 return resources.getString(R.string.api_pre_1_15);
347 return resources.getString(R.string.api_post_1_14);
349 throw new IllegalStateException("Unexpected value: " + value);