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