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