]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java
496624bf52475a6c22e6e2a2388d9d48d44aa53b
[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.os.AsyncTask;
21 import android.util.Log;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.ObjectWriter;
25
26 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
27 import net.ktnx.mobileledger.model.LedgerTransaction;
28 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
29 import net.ktnx.mobileledger.model.MobileLedgerProfile;
30 import net.ktnx.mobileledger.utils.Globals;
31 import net.ktnx.mobileledger.utils.Logger;
32 import net.ktnx.mobileledger.utils.NetworkUtil;
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.Date;
43 import java.util.GregorianCalendar;
44 import java.util.List;
45 import java.util.Locale;
46 import java.util.Map;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
49
50 import static android.os.SystemClock.sleep;
51 import static net.ktnx.mobileledger.utils.Logger.debug;
52
53 public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
54     private final TaskCallback taskCallback;
55     protected String error;
56     private String token;
57     private String session;
58     private LedgerTransaction ltr;
59     private MobileLedgerProfile mProfile;
60     private boolean simulate = false;
61
62     public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
63                                boolean simulate) {
64         taskCallback = callback;
65         mProfile = profile;
66         this.simulate = simulate;
67     }
68     public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
69         taskCallback = callback;
70         mProfile = profile;
71         simulate = false;
72     }
73     private boolean sendOK() throws IOException {
74         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
75         http.setRequestMethod("PUT");
76         http.setRequestProperty("Content-Type", "application/json");
77         http.setRequestProperty("Accept", "*/*");
78
79         ParsedLedgerTransaction jsonTransaction;
80         jsonTransaction = ltr.toParsedLedgerTransaction();
81         ObjectMapper mapper = new ObjectMapper();
82         ObjectWriter writer = mapper.writerFor(ParsedLedgerTransaction.class);
83         String body = writer.writeValueAsString(jsonTransaction);
84
85         if (simulate) {
86             debug("network", "The request would be: " + body);
87             try {
88                 Thread.sleep(1500);
89                 if (Math.random() > 0.3)
90                     throw new RuntimeException("Simulated test exception");
91             }
92             catch (InterruptedException ex) {
93                 Logger.debug("network", ex.toString());
94             }
95
96             return true;
97         }
98
99         byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
100         http.setDoOutput(true);
101         http.setDoInput(true);
102         http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
103
104         debug("network", "request header: " + http.getRequestProperties()
105                                                   .toString());
106
107         try (OutputStream req = http.getOutputStream()) {
108             debug("network", "Request body: " + body);
109             req.write(bodyBytes);
110
111             final int responseCode = http.getResponseCode();
112             debug("network",
113                     String.format("Response: %d %s", responseCode, http.getResponseMessage()));
114
115             try (InputStream resp = http.getErrorStream()) {
116
117                 switch (responseCode) {
118                     case 200:
119                     case 201:
120                         break;
121                     case 405:
122                         return false; // will cause a retry with the legacy method
123                     default:
124                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
125                         String line = reader.readLine();
126                         debug("network", "Response content: " + line);
127                         throw new IOException(
128                                 String.format("Error response code %d", responseCode));
129                 }
130             }
131         }
132
133         return true;
134     }
135     private boolean legacySendOK() throws IOException {
136         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
137         http.setRequestMethod("POST");
138         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
139         http.setRequestProperty("Accept", "*/*");
140         if ((session != null) && !session.isEmpty()) {
141             http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
142         }
143         http.setDoOutput(true);
144         http.setDoInput(true);
145
146         UrlEncodedFormData params = new UrlEncodedFormData();
147         params.addPair("_formid", "identify-add");
148         if (token != null)
149             params.addPair("_token", token);
150
151         Date transactionDate = ltr.getDate();
152         if (transactionDate == null) {
153             transactionDate = new GregorianCalendar().getTime();
154         }
155
156         params.addPair("date", Globals.formatLedgerDate(transactionDate));
157         params.addPair("description", ltr.getDescription());
158         for (LedgerTransactionAccount acc : ltr.getAccounts()) {
159             params.addPair("account", acc.getAccountName());
160             if (acc.isAmountSet())
161                 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
162             else
163                 params.addPair("amount", "");
164         }
165
166         String body = params.toString();
167         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
168
169         debug("network", "request header: " + http.getRequestProperties()
170                                                   .toString());
171
172         try (OutputStream req = http.getOutputStream()) {
173             debug("network", "Request body: " + body);
174             req.write(body.getBytes(StandardCharsets.US_ASCII));
175
176             try (InputStream resp = http.getInputStream()) {
177                 debug("update_accounts", String.valueOf(http.getResponseCode()));
178                 if (http.getResponseCode() == 303) {
179                     // everything is fine
180                     return true;
181                 }
182                 else if (http.getResponseCode() == 200) {
183                     // get the new cookie
184                     {
185                         Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
186
187                         Map<String, List<String>> header = http.getHeaderFields();
188                         List<String> cookieHeader = header.get("Set-Cookie");
189                         if (cookieHeader != null) {
190                             String cookie = cookieHeader.get(0);
191                             Matcher m = reSessionCookie.matcher(cookie);
192                             if (m.matches()) {
193                                 session = m.group(1);
194                                 debug("network", "new session is " + session);
195                             }
196                             else {
197                                 debug("network", "set-cookie: " + cookie);
198                                 Log.w("network",
199                                         "Response Set-Cookie headers is not a _SESSION one");
200                             }
201                         }
202                         else {
203                             Log.w("network", "Response has no Set-Cookie header");
204                         }
205                     }
206                     // the token needs to be updated
207                     BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
208                     Pattern re = Pattern.compile(
209                             "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
210                     String line;
211                     while ((line = reader.readLine()) != null) {
212                         //debug("dump", line);
213                         Matcher m = re.matcher(line);
214                         if (m.matches()) {
215                             token = m.group(1);
216                             debug("save-transaction", line);
217                             debug("save-transaction", "Token=" + token);
218                             return false;       // retry
219                         }
220                     }
221                     throw new IOException("Can't find _token string");
222                 }
223                 else {
224                     throw new IOException(
225                             String.format("Error response code %d", http.getResponseCode()));
226                 }
227             }
228         }
229     }
230
231     @Override
232     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
233         error = null;
234         try {
235             ltr = ledgerTransactions[0];
236
237             if (!sendOK()) {
238                 int tried = 0;
239                 while (!legacySendOK()) {
240                     tried++;
241                     if (tried >= 2)
242                         throw new IOException(String.format("aborting after %d tries", tried));
243                     sleep(100);
244                 }
245             }
246         }
247         catch (Exception e) {
248             e.printStackTrace();
249             error = e.getMessage();
250         }
251
252         return null;
253     }
254
255     @Override
256     protected void onPostExecute(Void aVoid) {
257         super.onPostExecute(aVoid);
258         taskCallback.done(error);
259     }
260 }