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.NetworkUtil;
27 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
29 import java.io.BufferedReader;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.io.OutputStream;
34 import java.net.HttpURLConnection;
35 import java.util.List;
36 import java.util.Locale;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
41 import static java.lang.Thread.sleep;
43 public class SaveTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
44 private final TaskCallback task_callback;
46 private String session;
47 private String backend_url;
48 private LedgerTransaction ltr;
49 protected String error;
51 public SaveTransactionTask(TaskCallback callback) {
52 task_callback = callback;
54 private boolean send_ok() throws IOException {
55 HttpURLConnection http = NetworkUtil.prepare_connection("add");
56 http.setRequestMethod("POST");
57 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
58 http.setRequestProperty("Accept", "*/*");
59 if ((session != null) && !session.isEmpty()) {
60 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
62 http.setDoOutput(true);
63 http.setDoInput(true);
65 UrlEncodedFormData params = new UrlEncodedFormData();
66 params.add_pair("_formid", "identify-add");
67 if (token != null) params.add_pair("_token", token);
68 params.add_pair("date", ltr.getDate());
69 params.add_pair("description", ltr.getDescription());
70 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
71 params.add_pair("account", acc.getAccountName());
72 if (acc.isAmountSet())
73 params.add_pair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
74 else params.add_pair("amount", "");
77 String body = params.toString();
78 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
80 Log.d("network", "request header: " + http.getRequestProperties().toString());
82 try (OutputStream req = http.getOutputStream()) {
83 Log.d("network", "Request body: " + body);
84 req.write(body.getBytes("ASCII"));
86 try (InputStream resp = http.getInputStream()) {
87 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
88 if (http.getResponseCode() == 303) {
91 } else if (http.getResponseCode() == 200) {
94 Pattern sess_cookie_re = Pattern.compile("_SESSION=([^;]+);.*");
96 Map<String, List<String>> header = http.getHeaderFields();
97 List<String> cookie_header = header.get("Set-Cookie");
98 if (cookie_header != null) {
99 String cookie = cookie_header.get(0);
100 Matcher m = sess_cookie_re.matcher(cookie);
102 session = m.group(1);
103 Log.d("network", "new session is " + session);
105 Log.d("network", "set-cookie: " + cookie);
106 Log.w("network", "Response Set-Cookie headers is not a _SESSION one");
109 Log.w("network", "Response has no Set-Cookie header");
112 // the token needs to be updated
113 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
114 Pattern re = Pattern.compile("<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
116 while ((line = reader.readLine()) != null) {
117 //Log.d("dump", line);
118 Matcher m = re.matcher(line);
121 Log.d("save-transaction", line);
122 Log.d("save-transaction", "Token=" + token);
123 return false; // retry
126 throw new IOException("Can't find _token string");
128 throw new IOException(String.format("Error response code %d", http.getResponseCode()));
135 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
138 backend_url = Data.profile.get().getUrl();
139 ltr = ledgerTransactions[0];
146 throw new IOException(String.format("aborting after %d tries", tried));
149 catch (InterruptedException e) {
154 catch (Exception e) {
156 error = e.getMessage();
163 protected void onPostExecute(Void aVoid) {
164 super.onPostExecute(aVoid);
165 task_callback.done(error);