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.
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.
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/>.
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.nio.charset.StandardCharsets;
37 import java.util.List;
38 import java.util.Locale;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
43 import static java.lang.Thread.sleep;
45 public class SaveTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
46 private final TaskCallback taskCallback;
47 protected String error;
49 private String session;
50 private String backendUrl;
51 private LedgerTransaction ltr;
53 public SaveTransactionTask(TaskCallback callback) {
54 taskCallback = callback;
56 private boolean sendOK() throws IOException {
57 HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add");
58 http.setRequestMethod("POST");
59 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
60 http.setRequestProperty("Accept", "*/*");
61 if ((session != null) && !session.isEmpty()) {
62 http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
64 http.setDoOutput(true);
65 http.setDoInput(true);
67 UrlEncodedFormData params = new UrlEncodedFormData();
68 params.addPair("_formid", "identify-add");
69 if (token != null) params.addPair("_token", token);
70 params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
71 params.addPair("description", ltr.getDescription());
72 for (LedgerTransactionAccount acc : ltr.getAccounts()) {
73 params.addPair("account", acc.getAccountName());
74 if (acc.isAmountSet())
75 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
76 else params.addPair("amount", "");
79 String body = params.toString();
80 http.addRequestProperty("Content-Length", String.valueOf(body.length()));
82 Log.d("network", "request header: " + http.getRequestProperties().toString());
84 try (OutputStream req = http.getOutputStream()) {
85 Log.d("network", "Request body: " + body);
86 req.write(body.getBytes(StandardCharsets.US_ASCII));
88 try (InputStream resp = http.getInputStream()) {
89 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
90 if (http.getResponseCode() == 303) {
94 else if (http.getResponseCode() == 200) {
97 Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
99 Map<String, List<String>> header = http.getHeaderFields();
100 List<String> cookieHeader = header.get("Set-Cookie");
101 if (cookieHeader != null) {
102 String cookie = cookieHeader.get(0);
103 Matcher m = reSessionCookie.matcher(cookie);
105 session = m.group(1);
106 Log.d("network", "new session is " + session);
109 Log.d("network", "set-cookie: " + cookie);
111 "Response Set-Cookie headers is not a _SESSION one");
115 Log.w("network", "Response has no Set-Cookie header");
118 // the token needs to be updated
119 BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
120 Pattern re = Pattern.compile(
121 "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
123 while ((line = reader.readLine()) != null) {
124 //Log.d("dump", line);
125 Matcher m = re.matcher(line);
128 Log.d("save-transaction", line);
129 Log.d("save-transaction", "Token=" + token);
130 return false; // retry
133 throw new IOException("Can't find _token string");
136 throw new IOException(
137 String.format("Error response code %d", http.getResponseCode()));
144 protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
147 backendUrl = Data.profile.get().getUrl();
148 ltr = ledgerTransactions[0];
155 throw new IOException(String.format("aborting after %d tries", tried));
158 catch (InterruptedException e) {
163 catch (Exception e) {
165 error = e.getMessage();
172 protected void onPostExecute(Void aVoid) {
173 super.onPostExecute(aVoid);
174 taskCallback.done(error);