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.os.AsyncTask;
21 import android.util.Log;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.ObjectWriter;
26 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
27 import net.ktnx.mobileledger.model.LedgerTransaction;
28 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
29 import net.ktnx.mobileledger.model.MobileLedgerProfile;
30 import net.ktnx.mobileledger.utils.Globals;
31 import net.ktnx.mobileledger.utils.NetworkUtil;
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;
49 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
50 private final TaskCallback taskCallback;
51 protected String error;
53 private String session;
54 private LedgerTransaction ltr;
55 private MobileLedgerProfile mProfile;
57 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
58 taskCallback = callback;
61 private boolean sendOK() throws IOException {
62 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
63 http.setRequestMethod("PUT");
64 http.setRequestProperty("Content-Type", "application/json");
65 http.setRequestProperty("Accept", "*/*");
67 ParsedLedgerTransaction jsonTransaction;
68 jsonTransaction = ltr.toParsedLedgerTransaction();
69 ObjectMapper mapper = new ObjectMapper();
70 ObjectWriter writer = mapper.writerFor(ParsedLedgerTransaction.class);
71 String body = writer.writeValueAsString(jsonTransaction);
73 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
74 http.setDoOutput(true);
75 http.setDoInput(true);
76 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
78 Log.d("network", "request header: " + http.getRequestProperties().toString());
80 try (OutputStream req = http.getOutputStream()) {
81 Log.d("network", "Request body: " + body);
84 final int responseCode = http.getResponseCode();
86 String.format("Response: %d %s", responseCode, http.getResponseMessage()));
88 try (InputStream resp = http.getErrorStream()) {
90 switch (responseCode) {
95 return false; // will cause a retry with the legacy method
97 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
98 String line = reader.readLine();
99 Log.d("network", "Response content: " + line);
100 throw new IOException(
101 String.format("Error response code %d", responseCode));
108 private boolean legacySendOK() throws IOException {
109 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
110 http.setRequestMethod("POST");
111 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
112 http.setRequestProperty("Accept", "*/*");
113 if ((session != null) && !session.isEmpty()) {
114 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
116 http.setDoOutput(true);
117 http.setDoInput(true);
119 UrlEncodedFormData params = new UrlEncodedFormData();
120 params.addPair("_formid", "identify-add");
121 if (token != null) params.addPair("_token", token);
122 params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
123 params.addPair("description", ltr.getDescription());
124 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
125 params.addPair("account", acc.getAccountName());
126 if (acc.isAmountSet())
127 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
128 else params.addPair("amount", "");
131 String body = params.toString();
132 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
134 Log.d("network", "request header: " + http.getRequestProperties().toString());
136 try (OutputStream req = http.getOutputStream()) {
137 Log.d("network", "Request body: " + body);
138 req.write(body.getBytes(StandardCharsets.US_ASCII));
140 try (InputStream resp = http.getInputStream()) {
141 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
142 if (http.getResponseCode() == 303) {
143 // everything is fine
146 else if (http.getResponseCode() == 200) {
147 // get the new cookie
149 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
151 Map<String, List<String>> header = http.getHeaderFields();
152 List<String> cookieHeader = header.get("Set-Cookie");
153 if (cookieHeader != null) {
154 String cookie = cookieHeader.get(0);
155 Matcher m = reSessionCookie.matcher(cookie);
157 session = m.group(1);
158 Log.d("network", "new session is " + session);
161 Log.d("network", "set-cookie: " + cookie);
163 "Response Set-Cookie headers is not a _SESSION one");
167 Log.w("network", "Response has no Set-Cookie header");
170 // the token needs to be updated
171 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
172 Pattern re = Pattern.compile(
173 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
175 while ((line = reader.readLine()) != null) {
176 //Log.d("dump", line);
177 Matcher m = re.matcher(line);
180 Log.d("save-transaction", line);
181 Log.d("save-transaction", "Token=" + token);
182 return false; // retry
185 throw new IOException("Can't find _token string");
188 throw new IOException(
189 String.format("Error response code %d", http.getResponseCode()));
196 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
199 ltr = ledgerTransactions[0];
203 while (!legacySendOK()) {
206 throw new IOException(String.format("aborting after %d tries", tried));
211 catch (Exception e) {
213 error = e.getMessage();
220 protected void onPostExecute(Void aVoid) {
221 super.onPostExecute(aVoid);
222 taskCallback.done(error);