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