]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java
drop shadow below the info about list freshness
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / SaveTransactionTask.java
1 /*
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.
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.LedgerTransactionItem;
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.Iterator;
36 import java.util.List;
37 import java.util.Locale;
38 import java.util.Map;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41
42 import static java.lang.Thread.sleep;
43
44 public class SaveTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
45     private final TaskCallback task_callback;
46     private String token;
47     private String session;
48     private String backend_url;
49     private LedgerTransaction ltr;
50     protected String error;
51
52     private SharedPreferences pref;
53     public void setPref(SharedPreferences pref) {
54         this.pref = pref;
55     }
56
57     public SaveTransactionTask(TaskCallback callback) {
58         task_callback = callback;
59     }
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));
67         }
68         http.setDoOutput(true);
69         http.setDoInput(true);
70
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());
76         {
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", "");
84             }
85         }
86
87         String body = params.toString();
88         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
89
90         Log.d("network", "request header: " + http.getRequestProperties().toString());
91
92         try (OutputStream req = http.getOutputStream()) {
93             Log.d("network", "Request body: " + body);
94             req.write(body.getBytes("ASCII"));
95
96             try (InputStream resp = http.getInputStream()) {
97                 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
98                 if (http.getResponseCode() == 303) {
99                     // everything is fine
100                     return true;
101                 } else if (http.getResponseCode() == 200) {
102                     // get the new cookie
103                     {
104                         Pattern sess_cookie_re = Pattern.compile("_SESSION=([^;]+);.*");
105
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);
111                             if (m.matches()) {
112                                 session = m.group(1);
113                                 Log.d("network", "new session is " + session);
114                             } else {
115                                 Log.d("network", "set-cookie: " + cookie);
116                                 Log.w("network", "Response Set-Cookie headers is not a _SESSION one");
117                             }
118                         } else {
119                             Log.w("network", "Response has no Set-Cookie header");
120                         }
121                     }
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=\"([^\"]+)\">");
125                     String line;
126                     while ((line = reader.readLine()) != null) {
127                         //Log.d("dump", line);
128                         Matcher m = re.matcher(line);
129                         if (m.matches()) {
130                             token = m.group(1);
131                             Log.d("save-transaction", line);
132                             Log.d("save-transaction", "Token=" + token);
133                             return false;       // retry
134                         }
135                     }
136                     throw new IOException("Can't find _token string");
137                 } else {
138                     throw new IOException(String.format("Error response code %d", http.getResponseCode()));
139                 }
140             }
141         }
142     }
143
144     @Override
145     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
146         error = null;
147         try {
148             backend_url = pref.getString("backend_url", "");
149             ltr = ledgerTransactions[0];
150
151             int tried = 0;
152             while (!send_ok()) {
153                 try {
154                     tried++;
155                     if (tried >= 2)
156                         throw new IOException(String.format("aborting after %d tries", tried));
157                     sleep(100);
158                 }
159                 catch (InterruptedException e) {
160                     e.printStackTrace();
161                 }
162             }
163         }
164         catch (Exception e) {
165             e.printStackTrace();
166             error = e.getMessage();
167         }
168
169         return null;
170     }
171
172     @Override
173     protected void onPostExecute(Void aVoid) {
174         super.onPostExecute(aVoid);
175         task_callback.done(error);
176     }
177 }