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