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