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.Data;
28 import net.ktnx.mobileledger.model.LedgerTransaction;
29 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
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;
56 public SendTransactionTask(TaskCallback callback) {
57 taskCallback = callback;
59 private boolean sendOK() throws IOException {
60 HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add");
61 http.setRequestMethod("PUT");
62 http.setRequestProperty("Content-Type", "application/json");
63 http.setRequestProperty("Accept", "*/*");
65 ParsedLedgerTransaction jsonTransaction;
66 jsonTransaction = ltr.toParsedLedgerTransaction();
67 ObjectMapper mapper = new ObjectMapper();
68 ObjectWriter writer = mapper.writerFor(ParsedLedgerTransaction.class);
69 String body = writer.writeValueAsString(jsonTransaction);
71 byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
72 http.setDoOutput(true);
73 http.setDoInput(true);
74 http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
76 Log.d("network", "request header: " + http.getRequestProperties().toString());
78 try (OutputStream req = http.getOutputStream()) {
79 Log.d("network", "Request body: " + body);
82 final int responseCode = http.getResponseCode();
84 String.format("Response: %d %s", responseCode, http.getResponseMessage()));
86 try (InputStream resp = http.getErrorStream()) {
88 switch (responseCode) {
93 return false; // will cause a retry with the legacy method
95 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
96 String line = reader.readLine();
97 Log.d("network", "Response content: " + line);
98 throw new IOException(
99 String.format("Error response code %d", responseCode));
106 private boolean legacySendOK() throws IOException {
107 HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add");
108 http.setRequestMethod("POST");
109 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
110 http.setRequestProperty("Accept", "*/*");
111 if ((session != null) && !session.isEmpty()) {
112 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
114 http.setDoOutput(true);
115 http.setDoInput(true);
117 UrlEncodedFormData params = new UrlEncodedFormData();
118 params.addPair("_formid", "identify-add");
119 if (token != null) params.addPair("_token", token);
120 params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
121 params.addPair("description", ltr.getDescription());
122 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
123 params.addPair("account", acc.getAccountName());
124 if (acc.isAmountSet())
125 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
126 else params.addPair("amount", "");
129 String body = params.toString();
130 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
132 Log.d("network", "request header: " + http.getRequestProperties().toString());
134 try (OutputStream req = http.getOutputStream()) {
135 Log.d("network", "Request body: " + body);
136 req.write(body.getBytes(StandardCharsets.US_ASCII));
138 try (InputStream resp = http.getInputStream()) {
139 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
140 if (http.getResponseCode() == 303) {
141 // everything is fine
144 else if (http.getResponseCode() == 200) {
145 // get the new cookie
147 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
149 Map<String, List<String>> header = http.getHeaderFields();
150 List<String> cookieHeader = header.get("Set-Cookie");
151 if (cookieHeader != null) {
152 String cookie = cookieHeader.get(0);
153 Matcher m = reSessionCookie.matcher(cookie);
155 session = m.group(1);
156 Log.d("network", "new session is " + session);
159 Log.d("network", "set-cookie: " + cookie);
161 "Response Set-Cookie headers is not a _SESSION one");
165 Log.w("network", "Response has no Set-Cookie header");
168 // the token needs to be updated
169 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
170 Pattern re = Pattern.compile(
171 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
173 while ((line = reader.readLine()) != null) {
174 //Log.d("dump", line);
175 Matcher m = re.matcher(line);
178 Log.d("save-transaction", line);
179 Log.d("save-transaction", "Token=" + token);
180 return false; // retry
183 throw new IOException("Can't find _token string");
186 throw new IOException(
187 String.format("Error response code %d", http.getResponseCode()));
194 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
197 ltr = ledgerTransactions[0];
201 while (!legacySendOK()) {
204 throw new IOException(String.format("aborting after %d tries", tried));
209 catch (Exception e) {
211 error = e.getMessage();
218 protected void onPostExecute(Void aVoid) {
219 super.onPostExecute(aVoid);
220 taskCallback.done(error);