]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java
1c4be5c47fea6789c6a22c3baa1b93928294775b
[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     private final MobileLedgerProfile mProfile;
63     private final boolean simulate;
64     protected String error;
65     private String token;
66     private String session;
67     private LedgerTransaction transaction;
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                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
152                         String line;
153                         int count = 0;
154                         while (count <= 5) {
155                             line = reader.readLine();
156                             if (line == null)
157                                 break;
158                             Logger.debug("network", line);
159                             count++;
160                         }
161                         return false; // will cause a retry with the legacy method
162                     }
163                     default:
164                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
165                         String line = reader.readLine();
166                         debug("network", "Response content: " + line);
167                         throw new IOException(
168                                 String.format("Error response code %d", responseCode));
169                 }
170             }
171         }
172
173         return true;
174     }
175     private boolean legacySendOK() throws IOException {
176         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
177         http.setRequestMethod("POST");
178         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
179         http.setRequestProperty("Accept", "*/*");
180         if ((session != null) && !session.isEmpty()) {
181             http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
182         }
183         http.setDoOutput(true);
184         http.setDoInput(true);
185
186         UrlEncodedFormData params = new UrlEncodedFormData();
187         params.addPair("_formid", "identify-add");
188         if (token != null)
189             params.addPair("_token", token);
190
191         SimpleDate transactionDate = transaction.getDateIfAny();
192         if (transactionDate == null)
193             transactionDate = SimpleDate.today();
194
195         params.addPair("date", Globals.formatLedgerDate(transactionDate));
196         params.addPair("description", transaction.getDescription());
197         for (LedgerTransactionAccount acc : transaction.getAccounts()) {
198             params.addPair("account", acc.getAccountName());
199             if (acc.isAmountSet())
200                 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
201             else
202                 params.addPair("amount", "");
203         }
204
205         String body = params.toString();
206         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
207
208         debug("network", "request header: " + http.getRequestProperties()
209                                                   .toString());
210
211         try (OutputStream req = http.getOutputStream()) {
212             debug("network", "Request body: " + body);
213             req.write(body.getBytes(StandardCharsets.US_ASCII));
214
215             try (InputStream resp = http.getInputStream()) {
216                 debug("update_accounts", String.valueOf(http.getResponseCode()));
217                 if (http.getResponseCode() == 303) {
218                     // everything is fine
219                     return true;
220                 }
221                 else if (http.getResponseCode() == 200) {
222                     // get the new cookie
223                     {
224                         Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
225
226                         Map<String, List<String>> header = http.getHeaderFields();
227                         List<String> cookieHeader = header.get("Set-Cookie");
228                         if (cookieHeader != null) {
229                             String cookie = cookieHeader.get(0);
230                             Matcher m = reSessionCookie.matcher(cookie);
231                             if (m.matches()) {
232                                 session = m.group(1);
233                                 debug("network", "new session is " + session);
234                             }
235                             else {
236                                 debug("network", "set-cookie: " + cookie);
237                                 Log.w("network",
238                                         "Response Set-Cookie headers is not a _SESSION one");
239                             }
240                         }
241                         else {
242                             Log.w("network", "Response has no Set-Cookie header");
243                         }
244                     }
245                     // the token needs to be updated
246                     BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
247                     Pattern re = Pattern.compile(
248                             "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
249                     String line;
250                     while ((line = reader.readLine()) != null) {
251                         //debug("dump", line);
252                         Matcher m = re.matcher(line);
253                         if (m.matches()) {
254                             token = m.group(1);
255                             debug("save-transaction", line);
256                             debug("save-transaction", "Token=" + token);
257                             return false;       // retry
258                         }
259                     }
260                     throw new IOException("Can't find _token string");
261                 }
262                 else {
263                     throw new IOException(
264                             String.format("Error response code %d", http.getResponseCode()));
265                 }
266             }
267         }
268     }
269     @Override
270     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
271         error = null;
272         try {
273             transaction = ledgerTransactions[0];
274
275             switch (mProfile.getApiVersion()) {
276                 case auto:
277                     Logger.debug("network", "Trying version 1.5.");
278                     if (!send_1_15_OK()) {
279                         Logger.debug("network", "Version 1.5 request failed. Trying with 1.14");
280                         if (!send_1_14_OK()) {
281                             Logger.debug("network",
282                                     "Version 1.14 failed too. Trying HTML form emulation");
283                             legacySendOkWithRetry();
284                         }
285                         else {
286                             Logger.debug("network", "Version 1.14 request succeeded");
287                         }
288                     }
289                     else {
290                         Logger.debug("network", "Version 1.15 request succeeded");
291                     }
292                     break;
293                 case html:
294                     legacySendOkWithRetry();
295                     break;
296                 case pre_1_15:
297                     send_1_14_OK();
298                     break;
299                 case post_1_14:
300                     send_1_15_OK();
301                     break;
302                 default:
303                     throw new IllegalStateException(
304                             "Unexpected API version: " + mProfile.getApiVersion());
305             }
306         }
307         catch (Exception e) {
308             e.printStackTrace();
309             error = e.getMessage();
310         }
311
312         return null;
313     }
314     private void legacySendOkWithRetry() throws IOException {
315         int tried = 0;
316         while (!legacySendOK()) {
317             tried++;
318             if (tried >= 2)
319                 throw new IOException(String.format("aborting after %d tries", tried));
320             sleep(100);
321         }
322     }
323     @Override
324     protected void onPostExecute(Void aVoid) {
325         super.onPostExecute(aVoid);
326         taskCallback.done(error);
327     }
328
329     public enum API {
330         auto(0), html(-1), pre_1_15(-2), post_1_14(-3);
331         private static final SparseArray<API> map = new SparseArray<>();
332
333         static {
334             for (API item : API.values()) {
335                 map.put(item.value, item);
336             }
337         }
338
339         private int value;
340
341         API(int value) {
342             this.value = value;
343         }
344         public static API valueOf(int i) {
345             return map.get(i, auto);
346         }
347         public int toInt() {
348             return this.value;
349         }
350         public String getDescription(Resources resources) {
351             switch (this) {
352                 case auto:
353                     return resources.getString(R.string.api_auto);
354                 case html:
355                     return resources.getString(R.string.api_html);
356                 case pre_1_15:
357                     return resources.getString(R.string.api_pre_1_15);
358                 case post_1_14:
359                     return resources.getString(R.string.api_post_1_14);
360                 default:
361                     throw new IllegalStateException("Unexpected value: " + value);
362             }
363         }
364     }
365 }