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 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
56 private final TaskCallback taskCallback;
57 protected String error;
59 private String session;
60 private LedgerTransaction ltr;
61 private MobileLedgerProfile mProfile;
62 private boolean simulate = false;
64 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
66 taskCallback = callback;
68 this.simulate = simulate;
70 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
71 taskCallback = callback;
75 private boolean send_1_15_OK() throws IOException {
76 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
77 http.setRequestMethod("PUT");
78 http.setRequestProperty("Content-Type", "application/json");
79 http.setRequestProperty("Accept", "*/*");
81 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction jsonTransaction =
82 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.fromLedgerTransaction(ltr);
83 ObjectMapper mapper = new ObjectMapper();
85 mapper.writerFor(net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.class);
86 String body = writer.writeValueAsString(jsonTransaction);
88 return sendRequest(http, body);
90 private boolean send_1_14_OK() throws IOException {
91 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
92 http.setRequestMethod("PUT");
93 http.setRequestProperty("Content-Type", "application/json");
94 http.setRequestProperty("Accept", "*/*");
96 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction jsonTransaction =
97 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.fromLedgerTransaction(ltr);
98 ObjectMapper mapper = new ObjectMapper();
100 mapper.writerFor(net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.class);
101 String body = writer.writeValueAsString(jsonTransaction);
103 return sendRequest(http, body);
105 private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
107 debug("network", "The request would be: " + body);
110 if (Math.random() > 0.3)
111 throw new RuntimeException("Simulated test exception");
113 catch (InterruptedException ex) {
114 Logger.debug("network", ex.toString());
120 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
121 http.setDoOutput(true);
122 http.setDoInput(true);
123 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
125 debug("network", "request header: " + http.getRequestProperties()
128 try (OutputStream req = http.getOutputStream()) {
129 debug("network", "Request body: " + body);
130 req.write(bodyBytes);
132 final int responseCode = http.getResponseCode();
134 String.format("Response: %d %s", responseCode, http.getResponseMessage()));
136 try (InputStream resp = http.getErrorStream()) {
138 switch (responseCode) {
144 return false; // will cause a retry with the legacy method
146 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
147 String line = reader.readLine();
148 debug("network", "Response content: " + line);
149 throw new IOException(
150 String.format("Error response code %d", responseCode));
157 private boolean legacySendOK() throws IOException {
158 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
159 http.setRequestMethod("POST");
160 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
161 http.setRequestProperty("Accept", "*/*");
162 if ((session != null) && !session.isEmpty()) {
163 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
165 http.setDoOutput(true);
166 http.setDoInput(true);
168 UrlEncodedFormData params = new UrlEncodedFormData();
169 params.addPair("_formid", "identify-add");
171 params.addPair("_token", token);
173 Date transactionDate = ltr.getDate();
174 if (transactionDate == null) {
175 transactionDate = new GregorianCalendar().getTime();
178 params.addPair("date", Globals.formatLedgerDate(transactionDate));
179 params.addPair("description", ltr.getDescription());
180 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
181 params.addPair("account", acc.getAccountName());
182 if (acc.isAmountSet())
183 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
185 params.addPair("amount", "");
188 String body = params.toString();
189 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
191 debug("network", "request header: " + http.getRequestProperties()
194 try (OutputStream req = http.getOutputStream()) {
195 debug("network", "Request body: " + body);
196 req.write(body.getBytes(StandardCharsets.US_ASCII));
198 try (InputStream resp = http.getInputStream()) {
199 debug("update_accounts", String.valueOf(http.getResponseCode()));
200 if (http.getResponseCode() == 303) {
201 // everything is fine
204 else if (http.getResponseCode() == 200) {
205 // get the new cookie
207 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
209 Map<String, List<String>> header = http.getHeaderFields();
210 List<String> cookieHeader = header.get("Set-Cookie");
211 if (cookieHeader != null) {
212 String cookie = cookieHeader.get(0);
213 Matcher m = reSessionCookie.matcher(cookie);
215 session = m.group(1);
216 debug("network", "new session is " + session);
219 debug("network", "set-cookie: " + cookie);
221 "Response Set-Cookie headers is not a _SESSION one");
225 Log.w("network", "Response has no Set-Cookie header");
228 // the token needs to be updated
229 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
230 Pattern re = Pattern.compile(
231 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
233 while ((line = reader.readLine()) != null) {
234 //debug("dump", line);
235 Matcher m = re.matcher(line);
238 debug("save-transaction", line);
239 debug("save-transaction", "Token=" + token);
240 return false; // retry
243 throw new IOException("Can't find _token string");
246 throw new IOException(
247 String.format("Error response code %d", http.getResponseCode()));
253 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
256 ltr = ledgerTransactions[0];
258 switch (mProfile.getApiVersion()) {
260 Logger.debug("network", "Trying version 1.5.");
261 if (!send_1_15_OK()) {
262 Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
263 if (!send_1_14_OK()) {
264 Logger.debug("network", "Version 1.14 failed too. Trying HTML form emulation");
265 legacySendOkWithRetry();
268 Logger.debug("network", "Version 1.14 request succeeded");
272 Logger.debug("network", "Version 1.15 request succeeded");
276 legacySendOkWithRetry();
285 throw new IllegalStateException(
286 "Unexpected API version: " + mProfile.getApiVersion());
289 catch (Exception e) {
291 error = e.getMessage();
296 private void legacySendOkWithRetry() throws IOException {
298 while (!legacySendOK()) {
301 throw new IOException(
302 String.format("aborting after %d tries", tried));
307 protected void onPostExecute(Void aVoid) {
308 super.onPostExecute(aVoid);
309 taskCallback.done(error);
313 auto(0), html(-1), pre_1_15(-2), post_1_14(-3);
314 private static SparseArray<API> map = new SparseArray<>();
317 for (API item : API.values()) {
318 map.put(item.value, item);
327 public static API valueOf(int i) {
328 return map.get(i, auto);
333 public String getDescription(Resources resources) {
336 return resources.getString(R.string.api_auto);
338 return resources.getString(R.string.api_html);
340 return resources.getString(R.string.api_pre_1_15);
342 return resources.getString(R.string.api_post_1_14);
344 throw new IllegalStateException("Unexpected value: " + value);