]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java
use profiles for connection parameters
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / SaveTransactionTask.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.async;
19
20 import android.content.SharedPreferences;
21 import android.os.AsyncTask;
22 import android.util.Log;
23
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;
28
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;
37 import java.util.Map;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 import static java.lang.Thread.sleep;
42
43 public class SaveTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
44     private final TaskCallback task_callback;
45     private String token;
46     private String session;
47     private String backend_url;
48     private LedgerTransaction ltr;
49     protected String error;
50
51     private SharedPreferences pref;
52     public void setPref(SharedPreferences pref) {
53         this.pref = pref;
54     }
55
56     public SaveTransactionTask(TaskCallback callback) {
57         task_callback = callback;
58     }
59     private boolean send_ok() throws IOException {
60         HttpURLConnection http = NetworkUtil.prepare_connection("add");
61         http.setRequestMethod("POST");
62         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
63         http.setRequestProperty("Accept", "*/*");
64         if ((session != null) && !session.isEmpty()) {
65             http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
66         }
67         http.setDoOutput(true);
68         http.setDoInput(true);
69
70         UrlEncodedFormData params = new UrlEncodedFormData();
71         params.add_pair("_formid", "identify-add");
72         if (token != null) params.add_pair("_token", token);
73         params.add_pair("date", ltr.getDate());
74         params.add_pair("description", ltr.getDescription());
75         for (LedgerTransactionAccount acc : ltr.getAccounts()) {
76             params.add_pair("account", acc.getAccountName());
77             if (acc.isAmountSet())
78                 params.add_pair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
79             else params.add_pair("amount", "");
80         }
81
82         String body = params.toString();
83         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
84
85         Log.d("network", "request header: " + http.getRequestProperties().toString());
86
87         try (OutputStream req = http.getOutputStream()) {
88             Log.d("network", "Request body: " + body);
89             req.write(body.getBytes("ASCII"));
90
91             try (InputStream resp = http.getInputStream()) {
92                 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
93                 if (http.getResponseCode() == 303) {
94                     // everything is fine
95                     return true;
96                 } else if (http.getResponseCode() == 200) {
97                     // get the new cookie
98                     {
99                         Pattern sess_cookie_re = Pattern.compile("_SESSION=([^;]+);.*");
100
101                         Map<String, List<String>> header = http.getHeaderFields();
102                         List<String> cookie_header = header.get("Set-Cookie");
103                         if (cookie_header != null) {
104                             String cookie = cookie_header.get(0);
105                             Matcher m = sess_cookie_re.matcher(cookie);
106                             if (m.matches()) {
107                                 session = m.group(1);
108                                 Log.d("network", "new session is " + session);
109                             } else {
110                                 Log.d("network", "set-cookie: " + cookie);
111                                 Log.w("network", "Response Set-Cookie headers is not a _SESSION one");
112                             }
113                         } else {
114                             Log.w("network", "Response has no Set-Cookie header");
115                         }
116                     }
117                     // the token needs to be updated
118                     BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
119                     Pattern re = Pattern.compile("<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
120                     String line;
121                     while ((line = reader.readLine()) != null) {
122                         //Log.d("dump", line);
123                         Matcher m = re.matcher(line);
124                         if (m.matches()) {
125                             token = m.group(1);
126                             Log.d("save-transaction", line);
127                             Log.d("save-transaction", "Token=" + token);
128                             return false;       // retry
129                         }
130                     }
131                     throw new IOException("Can't find _token string");
132                 } else {
133                     throw new IOException(String.format("Error response code %d", http.getResponseCode()));
134                 }
135             }
136         }
137     }
138
139     @Override
140     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
141         error = null;
142         try {
143             backend_url = pref.getString("backend_url", "");
144             ltr = ledgerTransactions[0];
145
146             int tried = 0;
147             while (!send_ok()) {
148                 try {
149                     tried++;
150                     if (tried >= 2)
151                         throw new IOException(String.format("aborting after %d tries", tried));
152                     sleep(100);
153                 }
154                 catch (InterruptedException e) {
155                     e.printStackTrace();
156                 }
157             }
158         }
159         catch (Exception e) {
160             e.printStackTrace();
161             error = e.getMessage();
162         }
163
164         return null;
165     }
166
167     @Override
168     protected void onPostExecute(Void aVoid) {
169         super.onPostExecute(aVoid);
170         task_callback.done(error);
171     }
172 }