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 net.ktnx.mobileledger.json.API;
24 import net.ktnx.mobileledger.json.Gateway;
25 import net.ktnx.mobileledger.model.LedgerTransaction;
26 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
27 import net.ktnx.mobileledger.model.MobileLedgerProfile;
28 import net.ktnx.mobileledger.utils.Globals;
29 import net.ktnx.mobileledger.utils.Logger;
30 import net.ktnx.mobileledger.utils.NetworkUtil;
31 import net.ktnx.mobileledger.utils.SimpleDate;
32 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
34 import java.io.BufferedReader;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.io.OutputStream;
39 import java.net.HttpURLConnection;
40 import java.nio.charset.StandardCharsets;
41 import java.util.List;
42 import java.util.Locale;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
47 import static android.os.SystemClock.sleep;
48 import static net.ktnx.mobileledger.utils.Logger.debug;
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 AsyncTask<LedgerTransaction, Void, Void> {
57 private final TaskCallback taskCallback;
58 private final MobileLedgerProfile mProfile;
59 private final boolean simulate;
60 protected String error;
62 private String session;
63 private LedgerTransaction transaction;
65 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
67 taskCallback = callback;
69 this.simulate = simulate;
71 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
72 taskCallback = callback;
76 private boolean sendOK(API apiVersion) throws IOException {
77 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
78 http.setRequestMethod("PUT");
79 http.setRequestProperty("Content-Type", "application/json");
80 http.setRequestProperty("Accept", "*/*");
82 Gateway gateway = Gateway.forApiVersion(apiVersion);
83 String body = gateway.transactionSaveRequest(transaction);
85 return sendRequest(http, body);
87 private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
89 debug("network", "The request would be: " + body);
92 if (Math.random() > 0.3)
93 throw new RuntimeException("Simulated test exception");
95 catch (InterruptedException ex) {
96 Logger.debug("network", ex.toString());
102 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
103 http.setDoOutput(true);
104 http.setDoInput(true);
105 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
107 debug("network", "request header: " + http.getRequestProperties()
110 try (OutputStream req = http.getOutputStream()) {
111 debug("network", "Request body: " + body);
112 req.write(bodyBytes);
114 final int responseCode = http.getResponseCode();
115 debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
116 http.getResponseMessage()));
118 try (InputStream resp = http.getErrorStream()) {
120 switch (responseCode) {
126 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
130 line = reader.readLine();
133 Logger.debug("network", line);
136 return false; // will cause a retry with another method
139 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
140 String line = reader.readLine();
141 debug("network", "Response content: " + line);
142 throw new IOException(
143 String.format("Error response code %d", responseCode));
150 private boolean legacySendOK() throws IOException {
151 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
152 http.setRequestMethod("POST");
153 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
154 http.setRequestProperty("Accept", "*/*");
155 if ((session != null) && !session.isEmpty()) {
156 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
158 http.setDoOutput(true);
159 http.setDoInput(true);
161 UrlEncodedFormData params = new UrlEncodedFormData();
162 params.addPair("_formid", "identify-add");
164 params.addPair("_token", token);
166 SimpleDate transactionDate = transaction.getDateIfAny();
167 if (transactionDate == null)
168 transactionDate = SimpleDate.today();
170 params.addPair("date", Globals.formatLedgerDate(transactionDate));
171 params.addPair("description", transaction.getDescription());
172 for (LedgerTransactionAccount acc : transaction.getAccounts()) {
173 params.addPair("account", acc.getAccountName());
174 if (acc.isAmountSet())
175 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
177 params.addPair("amount", "");
180 String body = params.toString();
181 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
183 debug("network", "request header: " + http.getRequestProperties()
186 try (OutputStream req = http.getOutputStream()) {
187 debug("network", "Request body: " + body);
188 req.write(body.getBytes(StandardCharsets.US_ASCII));
190 try (InputStream resp = http.getInputStream()) {
191 debug("update_accounts", String.valueOf(http.getResponseCode()));
192 if (http.getResponseCode() == 303) {
193 // everything is fine
196 else if (http.getResponseCode() == 200) {
197 // get the new cookie
199 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
201 Map<String, List<String>> header = http.getHeaderFields();
202 List<String> cookieHeader = header.get("Set-Cookie");
203 if (cookieHeader != null) {
204 String cookie = cookieHeader.get(0);
205 Matcher m = reSessionCookie.matcher(cookie);
207 session = m.group(1);
208 debug("network", "new session is " + session);
211 debug("network", "set-cookie: " + cookie);
213 "Response Set-Cookie headers is not a _SESSION one");
217 Log.w("network", "Response has no Set-Cookie header");
220 // the token needs to be updated
221 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
222 Pattern re = Pattern.compile(
223 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
225 while ((line = reader.readLine()) != null) {
226 //debug("dump", line);
227 Matcher m = re.matcher(line);
230 debug("save-transaction", line);
231 debug("save-transaction", "Token=" + token);
232 return false; // retry
235 throw new IOException("Can't find _token string");
238 throw new IOException(
239 String.format("Error response code %d", http.getResponseCode()));
245 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
248 transaction = ledgerTransactions[0];
250 final API profileApiVersion = mProfile.getApiVersion();
251 switch (profileApiVersion) {
253 boolean sendOK = false;
254 for (API ver : API.allVersions) {
255 Logger.debug("network", "Trying version " + ver);
258 Logger.debug("network", "Version " + ver + " request succeeded");
264 Logger.debug("network", "Trying HTML form emulation");
265 legacySendOkWithRetry();
269 legacySendOkWithRetry();
274 sendOK(profileApiVersion);
277 throw new IllegalStateException("Unexpected API version: " + profileApiVersion);
280 catch (Exception e) {
282 error = e.getMessage();
287 private void legacySendOkWithRetry() throws IOException {
289 while (!legacySendOK()) {
292 throw new IOException(String.format("aborting after %d tries", tried));
297 protected void onPostExecute(Void aVoid) {
298 super.onPostExecute(aVoid);
299 taskCallback.done(error);