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