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