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