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;
48 import static net.ktnx.mobileledger.utils.Logger.debug;
50 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
51 private final TaskCallback taskCallback;
52 protected String error;
54 private String session;
55 private LedgerTransaction ltr;
56 private MobileLedgerProfile mProfile;
58 public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
59 taskCallback = callback;
62 private boolean sendOK() throws IOException {
63 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
64 http.setRequestMethod("PUT");
65 http.setRequestProperty("Content-Type", "application/json");
66 http.setRequestProperty("Accept", "*/*");
68 ParsedLedgerTransaction jsonTransaction;
69 jsonTransaction = ltr.toParsedLedgerTransaction();
70 ObjectMapper mapper = new ObjectMapper();
71 ObjectWriter writer = mapper.writerFor(ParsedLedgerTransaction.class);
72 String body = writer.writeValueAsString(jsonTransaction);
74 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
75 http.setDoOutput(true);
76 http.setDoInput(true);
77 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
79 debug("network", "request header: " + http.getRequestProperties().toString());
81 try (OutputStream req = http.getOutputStream()) {
82 debug("network", "Request body: " + body);
85 final int responseCode = http.getResponseCode();
87 String.format("Response: %d %s", responseCode, http.getResponseMessage()));
89 try (InputStream resp = http.getErrorStream()) {
91 switch (responseCode) {
96 return false; // will cause a retry with the legacy method
98 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
99 String line = reader.readLine();
100 debug("network", "Response content: " + line);
101 throw new IOException(
102 String.format("Error response code %d", responseCode));
109 private boolean legacySendOK() throws IOException {
110 HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
111 http.setRequestMethod("POST");
112 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
113 http.setRequestProperty("Accept", "*/*");
114 if ((session != null) && !session.isEmpty()) {
115 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
117 http.setDoOutput(true);
118 http.setDoInput(true);
120 UrlEncodedFormData params = new UrlEncodedFormData();
121 params.addPair("_formid", "identify-add");
122 if (token != null) params.addPair("_token", token);
123 params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
124 params.addPair("description", ltr.getDescription());
125 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
126 params.addPair("account", acc.getAccountName());
127 if (acc.isAmountSet())
128 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
129 else params.addPair("amount", "");
132 String body = params.toString();
133 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
135 debug("network", "request header: " + http.getRequestProperties().toString());
137 try (OutputStream req = http.getOutputStream()) {
138 debug("network", "Request body: " + body);
139 req.write(body.getBytes(StandardCharsets.US_ASCII));
141 try (InputStream resp = http.getInputStream()) {
142 debug("update_accounts", String.valueOf(http.getResponseCode()));
143 if (http.getResponseCode() == 303) {
144 // everything is fine
147 else if (http.getResponseCode() == 200) {
148 // get the new cookie
150 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
152 Map<String, List<String>> header = http.getHeaderFields();
153 List<String> cookieHeader = header.get("Set-Cookie");
154 if (cookieHeader != null) {
155 String cookie = cookieHeader.get(0);
156 Matcher m = reSessionCookie.matcher(cookie);
158 session = m.group(1);
159 debug("network", "new session is " + session);
162 debug("network", "set-cookie: " + cookie);
164 "Response Set-Cookie headers is not a _SESSION one");
168 Log.w("network", "Response has no Set-Cookie header");
171 // the token needs to be updated
172 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
173 Pattern re = Pattern.compile(
174 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
176 while ((line = reader.readLine()) != null) {
177 //debug("dump", line);
178 Matcher m = re.matcher(line);
181 debug("save-transaction", line);
182 debug("save-transaction", "Token=" + token);
183 return false; // retry
186 throw new IOException("Can't find _token string");
189 throw new IOException(
190 String.format("Error response code %d", http.getResponseCode()));
197 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
200 ltr = ledgerTransactions[0];
204 while (!legacySendOK()) {
207 throw new IOException(String.format("aborting after %d tries", tried));
212 catch (Exception e) {
214 error = e.getMessage();
221 protected void onPostExecute(Void aVoid) {
222 super.onPostExecute(aVoid);
223 taskCallback.done(error);