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.db.Profile;
24 import net.ktnx.mobileledger.json.API;
25 import net.ktnx.mobileledger.json.ApiNotSupportedException;
26 import net.ktnx.mobileledger.json.Gateway;
27 import net.ktnx.mobileledger.model.LedgerTransaction;
28 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
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 Profile mProfile;
60 private final boolean simulate;
61 protected String error;
63 private String session;
64 private LedgerTransaction transaction;
66 public SendTransactionTask(TaskCallback callback, Profile profile,
68 taskCallback = callback;
70 this.simulate = simulate;
72 public SendTransactionTask(TaskCallback callback, Profile profile) {
73 taskCallback = callback;
77 private void sendOK(API apiVersion) throws IOException, ApiNotSupportedException {
78 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
79 http.setRequestMethod("PUT");
80 http.setRequestProperty("Content-Type", "application/json");
81 http.setRequestProperty("Accept", "*/*");
83 Gateway gateway = Gateway.forApiVersion(apiVersion);
84 String body = gateway.transactionSaveRequest(transaction);
86 Logger.debug("network", "Sending using API " + apiVersion);
87 sendRequest(http, body);
89 private void sendRequest(HttpURLConnection http, String body)
90 throws IOException, ApiNotSupportedException {
92 debug("network", "The request would be: " + body);
95 if (Math.random() > 0.3)
96 throw new RuntimeException("Simulated test exception");
98 catch (InterruptedException ex) {
99 Logger.debug("network", ex.toString());
105 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
106 http.setDoOutput(true);
107 http.setDoInput(true);
108 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
110 debug("network", "request header: " + http.getRequestProperties()
113 try (OutputStream req = http.getOutputStream()) {
114 debug("network", "Request body: " + body);
115 req.write(bodyBytes);
117 final int responseCode = http.getResponseCode();
118 debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
119 http.getResponseMessage()));
121 try (InputStream resp = http.getErrorStream()) {
123 switch (responseCode) {
129 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
130 StringBuilder errorLines = new StringBuilder();
133 String line = reader.readLine();
136 Logger.debug("network", line);
138 if (errorLines.length() != 0)
139 errorLines.append("\n");
141 errorLines.append(line);
144 throw new ApiNotSupportedException(errorLines.toString());
147 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
148 String line = reader.readLine();
149 debug("network", "Response content: " + line);
150 throw new IOException(
151 String.format("Error response code %d", responseCode));
156 private boolean legacySendOK() throws IOException {
157 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
158 http.setRequestMethod("POST");
159 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
160 http.setRequestProperty("Accept", "*/*");
161 if ((session != null) && !session.isEmpty()) {
162 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
164 http.setDoOutput(true);
165 http.setDoInput(true);
167 UrlEncodedFormData params = new UrlEncodedFormData();
168 params.addPair("_formid", "identify-add");
170 params.addPair("_token", token);
172 SimpleDate transactionDate = transaction.getDateIfAny();
173 if (transactionDate == null)
174 transactionDate = SimpleDate.today();
176 params.addPair("date", Globals.formatLedgerDate(transactionDate));
177 params.addPair("description", transaction.getDescription());
178 for (LedgerTransactionAccount acc : transaction.getAccounts()) {
179 params.addPair("account", acc.getAccountName());
180 if (acc.isAmountSet())
181 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
183 params.addPair("amount", "");
186 String body = params.toString();
187 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
189 debug("network", "request header: " + http.getRequestProperties()
192 try (OutputStream req = http.getOutputStream()) {
193 debug("network", "Request body: " + body);
194 req.write(body.getBytes(StandardCharsets.US_ASCII));
196 try (InputStream resp = http.getInputStream()) {
197 debug("update_accounts", String.valueOf(http.getResponseCode()));
198 if (http.getResponseCode() == 303) {
199 // everything is fine
202 else if (http.getResponseCode() == 200) {
203 // get the new cookie
205 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
207 Map<String, List<String>> header = http.getHeaderFields();
208 List<String> cookieHeader = header.get("Set-Cookie");
209 if (cookieHeader != null) {
210 String cookie = cookieHeader.get(0);
211 Matcher m = reSessionCookie.matcher(cookie);
213 session = m.group(1);
214 debug("network", "new session is " + session);
217 debug("network", "set-cookie: " + cookie);
219 "Response Set-Cookie headers is not a _SESSION one");
223 Log.w("network", "Response has no Set-Cookie header");
226 // the token needs to be updated
227 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
228 Pattern re = Pattern.compile(
229 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
231 while ((line = reader.readLine()) != null) {
232 //debug("dump", line);
233 Matcher m = re.matcher(line);
236 debug("save-transaction", line);
237 debug("save-transaction", "Token=" + token);
238 return false; // retry
241 throw new IOException("Can't find _token string");
244 throw new IOException(
245 String.format("Error response code %d", http.getResponseCode()));
251 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
254 transaction = ledgerTransactions[0];
256 final API profileApiVersion = API.valueOf(mProfile.getApiVersion());
257 switch (profileApiVersion) {
259 boolean sendOK = false;
260 for (API ver : API.allVersions) {
261 Logger.debug("network", "Trying version " + ver);
265 Logger.debug("network", "Version " + ver + " request succeeded");
269 catch (ApiNotSupportedException e) {
270 Logger.debug("network", "Version " + ver + " seems not supported");
275 Logger.debug("network", "Trying HTML form emulation");
276 legacySendOkWithRetry();
280 legacySendOkWithRetry();
285 sendOK(profileApiVersion);
288 throw new IllegalStateException("Unexpected API version: " + profileApiVersion);
291 catch (ApiNotSupportedException | Exception e) {
293 error = e.getMessage();
298 private void legacySendOkWithRetry() throws IOException {
300 while (!legacySendOK()) {
303 throw new IOException(String.format("aborting after %d tries", tried));
308 protected void onPostExecute(Void aVoid) {
309 super.onPostExecute(aVoid);
310 taskCallback.done(error);