2 * Copyright © 2018 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.content.SharedPreferences;
21 import android.os.AsyncTask;
22 import android.util.Log;
24 import net.ktnx.mobileledger.model.LedgerTransaction;
25 import net.ktnx.mobileledger.model.LedgerTransactionItem;
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.Iterator;
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 task_callback;
47 private String session;
48 private String backend_url;
49 private LedgerTransaction ltr;
50 protected String error;
52 private SharedPreferences pref;
53 public void setPref(SharedPreferences pref) {
57 public SaveTransactionTask(TaskCallback callback) {
58 task_callback = callback;
60 private boolean send_ok() throws IOException {
61 HttpURLConnection http = NetworkUtil.prepare_connection(pref, "add");
62 http.setRequestMethod("POST");
63 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
64 http.setRequestProperty("Accept", "*/*");
65 if ((session != null) && !session.isEmpty()) {
66 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
68 http.setDoOutput(true);
69 http.setDoInput(true);
71 UrlEncodedFormData params = new UrlEncodedFormData();
72 params.add_pair("_formid", "identify-add");
73 if (token != null) params.add_pair("_token", token);
74 params.add_pair("date", ltr.getDate());
75 params.add_pair("description", ltr.getDescription());
77 Iterator<LedgerTransactionItem> items = ltr.getItemsIterator();
78 while (items.hasNext()) {
79 LedgerTransactionItem item = items.next();
80 params.add_pair("account", item.getAccountName());
81 if (item.isAmountSet())
82 params.add_pair("amount", String.format(Locale.US, "%1.2f", item.getAmount()));
83 else params.add_pair("amount", "");
87 String body = params.toString();
88 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
90 Log.d("network", "request header: " + http.getRequestProperties().toString());
92 try (OutputStream req = http.getOutputStream()) {
93 Log.d("network", "Request body: " + body);
94 req.write(body.getBytes("ASCII"));
96 try (InputStream resp = http.getInputStream()) {
97 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
98 if (http.getResponseCode() == 303) {
101 } else if (http.getResponseCode() == 200) {
102 // get the new cookie
104 Pattern sess_cookie_re = Pattern.compile("_SESSION=([^;]+);.*");
106 Map<String, List<String>> header = http.getHeaderFields();
107 List<String> cookie_header = header.get("Set-Cookie");
108 if (cookie_header != null) {
109 String cookie = cookie_header.get(0);
110 Matcher m = sess_cookie_re.matcher(cookie);
112 session = m.group(1);
113 Log.d("network", "new session is " + session);
115 Log.d("network", "set-cookie: " + cookie);
116 Log.w("network", "Response Set-Cookie headers is not a _SESSION one");
119 Log.w("network", "Response has no Set-Cookie header");
122 // the token needs to be updated
123 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
124 Pattern re = Pattern.compile("<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
126 while ((line = reader.readLine()) != null) {
127 //Log.d("dump", line);
128 Matcher m = re.matcher(line);
131 Log.d("save-transaction", line);
132 Log.d("save-transaction", "Token=" + token);
133 return false; // retry
136 throw new IOException("Can't find _token string");
138 throw new IOException(String.format("Error response code %d", http.getResponseCode()));
145 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
148 backend_url = pref.getString("backend_url", "");
149 ltr = ledgerTransactions[0];
156 throw new IOException(String.format("aborting after %d tries", tried));
159 catch (InterruptedException e) {
164 catch (Exception e) {
166 error = e.getMessage();
173 protected void onPostExecute(Void aVoid) {
174 super.onPostExecute(aVoid);
175 task_callback.done(error);