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