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