]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java
dc0c24875469a74b5d6404097a21034d1690672a
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / SendTransactionTask.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.async;
19
20 import android.os.AsyncTask;
21 import android.util.Log;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.ObjectWriter;
25
26 import net.ktnx.mobileledger.model.LedgerTransaction;
27 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
28 import net.ktnx.mobileledger.model.MobileLedgerProfile;
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;
34
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;
44 import java.util.Map;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47
48 import static android.os.SystemClock.sleep;
49 import static net.ktnx.mobileledger.utils.Logger.debug;
50
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
55  */
56
57 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
58     private final TaskCallback taskCallback;
59     private final MobileLedgerProfile mProfile;
60     private final boolean simulate;
61     protected String error;
62     private String token;
63     private String session;
64     private LedgerTransaction transaction;
65
66     public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
67                                boolean simulate) {
68         taskCallback = callback;
69         mProfile = profile;
70         this.simulate = simulate;
71     }
72     public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
73         taskCallback = callback;
74         mProfile = profile;
75         simulate = false;
76     }
77     private boolean send_1_15_OK() throws IOException {
78         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
79         http.setRequestMethod("PUT");
80         http.setRequestProperty("Content-Type", "application/json");
81         http.setRequestProperty("Accept", "*/*");
82
83         net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction jsonTransaction =
84                 net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.fromLedgerTransaction(
85                         transaction);
86         ObjectMapper mapper = new ObjectMapper();
87         ObjectWriter writer =
88                 mapper.writerFor(net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction.class);
89         String body = writer.writeValueAsString(jsonTransaction);
90
91         return sendRequest(http, body);
92     }
93     private boolean send_1_14_OK() throws IOException {
94         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
95         http.setRequestMethod("PUT");
96         http.setRequestProperty("Content-Type", "application/json");
97         http.setRequestProperty("Accept", "*/*");
98
99         net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction jsonTransaction =
100                 net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.fromLedgerTransaction(
101                         transaction);
102         ObjectMapper mapper = new ObjectMapper();
103         ObjectWriter writer =
104                 mapper.writerFor(net.ktnx.mobileledger.json.v1_14.ParsedLedgerTransaction.class);
105         String body = writer.writeValueAsString(jsonTransaction);
106
107         return sendRequest(http, body);
108     }
109     private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
110         if (simulate) {
111             debug("network", "The request would be: " + body);
112             try {
113                 Thread.sleep(1500);
114                 if (Math.random() > 0.3)
115                     throw new RuntimeException("Simulated test exception");
116             }
117             catch (InterruptedException ex) {
118                 Logger.debug("network", ex.toString());
119             }
120
121             return true;
122         }
123
124         byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
125         http.setDoOutput(true);
126         http.setDoInput(true);
127         http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
128
129         debug("network", "request header: " + http.getRequestProperties()
130                                                   .toString());
131
132         try (OutputStream req = http.getOutputStream()) {
133             debug("network", "Request body: " + body);
134             req.write(bodyBytes);
135
136             final int responseCode = http.getResponseCode();
137             debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
138                     http.getResponseMessage()));
139
140             try (InputStream resp = http.getErrorStream()) {
141
142                 switch (responseCode) {
143                     case 200:
144                     case 201:
145                         break;
146                     case 400:
147                     case 405: {
148                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
149                         String line;
150                         int count = 0;
151                         while (count <= 5) {
152                             line = reader.readLine();
153                             if (line == null)
154                                 break;
155                             Logger.debug("network", line);
156                             count++;
157                         }
158                         return false; // will cause a retry with the legacy method
159                     }
160                     default:
161                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
162                         String line = reader.readLine();
163                         debug("network", "Response content: " + line);
164                         throw new IOException(
165                                 String.format("Error response code %d", responseCode));
166                 }
167             }
168         }
169
170         return true;
171     }
172     private boolean legacySendOK() throws IOException {
173         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
174         http.setRequestMethod("POST");
175         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
176         http.setRequestProperty("Accept", "*/*");
177         if ((session != null) && !session.isEmpty()) {
178             http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
179         }
180         http.setDoOutput(true);
181         http.setDoInput(true);
182
183         UrlEncodedFormData params = new UrlEncodedFormData();
184         params.addPair("_formid", "identify-add");
185         if (token != null)
186             params.addPair("_token", token);
187
188         SimpleDate transactionDate = transaction.getDateIfAny();
189         if (transactionDate == null)
190             transactionDate = SimpleDate.today();
191
192         params.addPair("date", Globals.formatLedgerDate(transactionDate));
193         params.addPair("description", transaction.getDescription());
194         for (LedgerTransactionAccount acc : transaction.getAccounts()) {
195             params.addPair("account", acc.getAccountName());
196             if (acc.isAmountSet())
197                 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
198             else
199                 params.addPair("amount", "");
200         }
201
202         String body = params.toString();
203         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
204
205         debug("network", "request header: " + http.getRequestProperties()
206                                                   .toString());
207
208         try (OutputStream req = http.getOutputStream()) {
209             debug("network", "Request body: " + body);
210             req.write(body.getBytes(StandardCharsets.US_ASCII));
211
212             try (InputStream resp = http.getInputStream()) {
213                 debug("update_accounts", String.valueOf(http.getResponseCode()));
214                 if (http.getResponseCode() == 303) {
215                     // everything is fine
216                     return true;
217                 }
218                 else if (http.getResponseCode() == 200) {
219                     // get the new cookie
220                     {
221                         Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
222
223                         Map<String, List<String>> header = http.getHeaderFields();
224                         List<String> cookieHeader = header.get("Set-Cookie");
225                         if (cookieHeader != null) {
226                             String cookie = cookieHeader.get(0);
227                             Matcher m = reSessionCookie.matcher(cookie);
228                             if (m.matches()) {
229                                 session = m.group(1);
230                                 debug("network", "new session is " + session);
231                             }
232                             else {
233                                 debug("network", "set-cookie: " + cookie);
234                                 Log.w("network",
235                                         "Response Set-Cookie headers is not a _SESSION one");
236                             }
237                         }
238                         else {
239                             Log.w("network", "Response has no Set-Cookie header");
240                         }
241                     }
242                     // the token needs to be updated
243                     BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
244                     Pattern re = Pattern.compile(
245                             "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
246                     String line;
247                     while ((line = reader.readLine()) != null) {
248                         //debug("dump", line);
249                         Matcher m = re.matcher(line);
250                         if (m.matches()) {
251                             token = m.group(1);
252                             debug("save-transaction", line);
253                             debug("save-transaction", "Token=" + token);
254                             return false;       // retry
255                         }
256                     }
257                     throw new IOException("Can't find _token string");
258                 }
259                 else {
260                     throw new IOException(
261                             String.format("Error response code %d", http.getResponseCode()));
262                 }
263             }
264         }
265     }
266     @Override
267     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
268         error = null;
269         try {
270             transaction = ledgerTransactions[0];
271
272             switch (mProfile.getApiVersion()) {
273                 case auto:
274                     Logger.debug("network", "Trying version 1.5.");
275                     if (!send_1_15_OK()) {
276                         Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
277                         if (!send_1_14_OK()) {
278                             Logger.debug("network",
279                                     "Version 1.14 failed too. Trying HTML form emulation");
280                             legacySendOkWithRetry();
281                         }
282                         else {
283                             Logger.debug("network", "Version 1.14 request succeeded");
284                         }
285                     }
286                     else {
287                         Logger.debug("network", "Version 1.15 request succeeded");
288                     }
289                     break;
290                 case html:
291                     legacySendOkWithRetry();
292                     break;
293                 case v1_14:
294                     send_1_14_OK();
295                     break;
296                 case v1_15:
297                     send_1_15_OK();
298                     break;
299                 default:
300                     throw new IllegalStateException(
301                             "Unexpected API version: " + mProfile.getApiVersion());
302             }
303         }
304         catch (Exception e) {
305             e.printStackTrace();
306             error = e.getMessage();
307         }
308
309         return null;
310     }
311     private void legacySendOkWithRetry() throws IOException {
312         int tried = 0;
313         while (!legacySendOK()) {
314             tried++;
315             if (tried >= 2)
316                 throw new IOException(String.format("aborting after %d tries", tried));
317             sleep(100);
318         }
319     }
320     @Override
321     protected void onPostExecute(Void aVoid) {
322         super.onPostExecute(aVoid);
323         taskCallback.done(error);
324     }
325
326 }