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