2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of Mobile-Ledger.
4 * Mobile-Ledger 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.
9 * Mobile-Ledger 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.
14 * You should have received a copy of the GNU General Public License
15 * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.async;
20 import android.os.AsyncTask;
21 import android.util.Log;
23 import net.ktnx.mobileledger.model.Data;
24 import net.ktnx.mobileledger.model.LedgerTransaction;
25 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
26 import net.ktnx.mobileledger.utils.Globals;
27 import net.ktnx.mobileledger.utils.NetworkUtil;
28 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
30 import java.io.BufferedReader;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.OutputStream;
35 import java.net.HttpURLConnection;
36 import java.util.List;
37 import java.util.Locale;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
42 import static java.lang.Thread.sleep;
44 public class SaveTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
45 private final TaskCallback taskCallback;
46 protected String error;
48 private String session;
49 private String backendUrl;
50 private LedgerTransaction ltr;
52 public SaveTransactionTask(TaskCallback callback) {
53 taskCallback = callback;
55 private boolean sendOK() throws IOException {
56 HttpURLConnection http = NetworkUtil.prepareConnection("add");
57 http.setRequestMethod("POST");
58 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
59 http.setRequestProperty("Accept", "*/*");
60 if ((session != null) && !session.isEmpty()) {
61 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
63 http.setDoOutput(true);
64 http.setDoInput(true);
66 UrlEncodedFormData params = new UrlEncodedFormData();
67 params.addPair("_formid", "identify-add");
68 if (token != null) params.addPair("_token", token);
69 params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
70 params.addPair("description", ltr.getDescription());
71 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
72 params.addPair("account", acc.getAccountName());
73 if (acc.isAmountSet())
74 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
75 else params.addPair("amount", "");
78 String body = params.toString();
79 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
81 Log.d("network", "request header: " + http.getRequestProperties().toString());
83 try (OutputStream req = http.getOutputStream()) {
84 Log.d("network", "Request body: " + body);
85 req.write(body.getBytes("ASCII"));
87 try (InputStream resp = http.getInputStream()) {
88 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
89 if (http.getResponseCode() == 303) {
93 else if (http.getResponseCode() == 200) {
96 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
98 Map<String, List<String>> header = http.getHeaderFields();
99 List<String> cookieHeader = header.get("Set-Cookie");
100 if (cookieHeader != null) {
101 String cookie = cookieHeader.get(0);
102 Matcher m = reSessionCookie.matcher(cookie);
104 session = m.group(1);
105 Log.d("network", "new session is " + session);
108 Log.d("network", "set-cookie: " + cookie);
110 "Response Set-Cookie headers is not a _SESSION one");
114 Log.w("network", "Response has no Set-Cookie header");
117 // the token needs to be updated
118 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
119 Pattern re = Pattern.compile(
120 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
122 while ((line = reader.readLine()) != null) {
123 //Log.d("dump", line);
124 Matcher m = re.matcher(line);
127 Log.d("save-transaction", line);
128 Log.d("save-transaction", "Token=" + token);
129 return false; // retry
132 throw new IOException("Can't find _token string");
135 throw new IOException(
136 String.format("Error response code %d", http.getResponseCode()));
143 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
146 backendUrl = Data.profile.get().getUrl();
147 ltr = ledgerTransactions[0];
154 throw new IOException(String.format("aborting after %d tries", tried));
157 catch (InterruptedException e) {
162 catch (Exception e) {
164 error = e.getMessage();
171 protected void onPostExecute(Void aVoid) {
172 super.onPostExecute(aVoid);
173 taskCallback.done(error);