2 * Copyright © 2019 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.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.Date;
45 import java.util.GregorianCalendar;
46 import java.util.List;
47 import java.util.Locale;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
52 import static android.os.SystemClock.sleep;
53 import static net.ktnx.mobileledger.utils.Logger.debug;
55 /* TODO: get rid of the custom session/cookie and auth code?
56 * (the last problem with the POST was the missing content-length header)
57 * This will resolve itself when hledger-web 1.14+ is released with Debian/stable,
58 * at which point the HTML form emulation can be dropped entirely
61 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
62 private final TaskCallback taskCallback;
63 protected String error;
65 private String session;
66 private LedgerTransaction ltr;
67 private MobileLedgerProfile mProfile;
68 private boolean simulate = false;
70 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
72 taskCallback = callback;
74 this.simulate = simulate;
76 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
77 taskCallback = callback;
81 private boolean send_1_15_OK() throws IOException {
82 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
83 http.setRequestMethod("PUT");
84 http.setRequestProperty("Content-Type", "application/json");
85 http.setRequestProperty("Accept", "*/*");
87 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction jsonTransaction =
88 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.fromLedgerTransaction(ltr);
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(ltr);
104 ObjectMapper mapper = new ObjectMapper();
105 ObjectWriter writer =
106 mapper.writerFor(net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.class);
107 String body = writer.writeValueAsString(jsonTransaction);
109 return sendRequest(http, body);
111 private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
113 debug("network", "The request would be: " + body);
116 if (Math.random() > 0.3)
117 throw new RuntimeException("Simulated test exception");
119 catch (InterruptedException ex) {
120 Logger.debug("network", ex.toString());
126 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
127 http.setDoOutput(true);
128 http.setDoInput(true);
129 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
131 debug("network", "request header: " + http.getRequestProperties()
134 try (OutputStream req = http.getOutputStream()) {
135 debug("network", "Request body: " + body);
136 req.write(bodyBytes);
138 final int responseCode = http.getResponseCode();
140 String.format("Response: %d %s", responseCode, http.getResponseMessage()));
142 try (InputStream resp = http.getErrorStream()) {
144 switch (responseCode) {
150 return false; // will cause a retry with the legacy method
152 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
153 String line = reader.readLine();
154 debug("network", "Response content: " + line);
155 throw new IOException(
156 String.format("Error response code %d", responseCode));
163 private boolean legacySendOK() throws IOException {
164 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
165 http.setRequestMethod("POST");
166 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
167 http.setRequestProperty("Accept", "*/*");
168 if ((session != null) && !session.isEmpty()) {
169 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
171 http.setDoOutput(true);
172 http.setDoInput(true);
174 UrlEncodedFormData params = new UrlEncodedFormData();
175 params.addPair("_formid", "identify-add");
177 params.addPair("_token", token);
179 Date transactionDate = ltr.getDate();
180 if (transactionDate == null) {
181 transactionDate = new GregorianCalendar().getTime();
184 params.addPair("date", Globals.formatLedgerDate(transactionDate));
185 params.addPair("description", ltr.getDescription());
186 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
187 params.addPair("account", acc.getAccountName());
188 if (acc.isAmountSet())
189 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
191 params.addPair("amount", "");
194 String body = params.toString();
195 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
197 debug("network", "request header: " + http.getRequestProperties()
200 try (OutputStream req = http.getOutputStream()) {
201 debug("network", "Request body: " + body);
202 req.write(body.getBytes(StandardCharsets.US_ASCII));
204 try (InputStream resp = http.getInputStream()) {
205 debug("update_accounts", String.valueOf(http.getResponseCode()));
206 if (http.getResponseCode() == 303) {
207 // everything is fine
210 else if (http.getResponseCode() == 200) {
211 // get the new cookie
213 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
215 Map<String, List<String>> header = http.getHeaderFields();
216 List<String> cookieHeader = header.get("Set-Cookie");
217 if (cookieHeader != null) {
218 String cookie = cookieHeader.get(0);
219 Matcher m = reSessionCookie.matcher(cookie);
221 session = m.group(1);
222 debug("network", "new session is " + session);
225 debug("network", "set-cookie: " + cookie);
227 "Response Set-Cookie headers is not a _SESSION one");
231 Log.w("network", "Response has no Set-Cookie header");
234 // the token needs to be updated
235 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
236 Pattern re = Pattern.compile(
237 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
239 while ((line = reader.readLine()) != null) {
240 //debug("dump", line);
241 Matcher m = re.matcher(line);
244 debug("save-transaction", line);
245 debug("save-transaction", "Token=" + token);
246 return false; // retry
249 throw new IOException("Can't find _token string");
252 throw new IOException(
253 String.format("Error response code %d", http.getResponseCode()));
259 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
262 ltr = ledgerTransactions[0];
264 switch (mProfile.getApiVersion()) {
266 Logger.debug("network", "Trying version 1.5.");
267 if (!send_1_15_OK()) {
268 Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
269 if (!send_1_14_OK()) {
270 Logger.debug("network",
271 "Version 1.14 failed too. Trying HTML form emulation");
272 legacySendOkWithRetry();
275 Logger.debug("network", "Version 1.14 request succeeded");
279 Logger.debug("network", "Version 1.15 request succeeded");
283 legacySendOkWithRetry();
292 throw new IllegalStateException(
293 "Unexpected API version: " + mProfile.getApiVersion());
296 catch (Exception e) {
298 error = e.getMessage();
303 private void legacySendOkWithRetry() throws IOException {
305 while (!legacySendOK()) {
308 throw new IOException(String.format("aborting after %d tries", tried));
313 protected void onPostExecute(Void aVoid) {
314 super.onPostExecute(aVoid);
315 taskCallback.done(error);
319 auto(0), html(-1), pre_1_15(-2), post_1_14(-3);
320 private static SparseArray<API> map = new SparseArray<>();
323 for (API item : API.values()) {
324 map.put(item.value, item);
333 public static API valueOf(int i) {
334 return map.get(i, auto);
339 public String getDescription(Resources resources) {
342 return resources.getString(R.string.api_auto);
344 return resources.getString(R.string.api_html);
346 return resources.getString(R.string.api_pre_1_15);
348 return resources.getString(R.string.api_post_1_14);
350 throw new IllegalStateException("Unexpected value: " + value);