]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java
two more lambdas
[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.os.AsyncTask;
21 import android.util.Log;
22
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;
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     public SaveTransactionTask(TaskCallback callback) {
52         task_callback = callback;
53     }
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));
61         }
62         http.setDoOutput(true);
63         http.setDoInput(true);
64
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", "");
75         }
76
77         String body = params.toString();
78         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
79
80         Log.d("network", "request header: " + http.getRequestProperties().toString());
81
82         try (OutputStream req = http.getOutputStream()) {
83             Log.d("network", "Request body: " + body);
84             req.write(body.getBytes("ASCII"));
85
86             try (InputStream resp = http.getInputStream()) {
87                 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
88                 if (http.getResponseCode() == 303) {
89                     // everything is fine
90                     return true;
91                 } else if (http.getResponseCode() == 200) {
92                     // get the new cookie
93                     {
94                         Pattern sess_cookie_re = Pattern.compile("_SESSION=([^;]+);.*");
95
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);
101                             if (m.matches()) {
102                                 session = m.group(1);
103                                 Log.d("network", "new session is " + session);
104                             } else {
105                                 Log.d("network", "set-cookie: " + cookie);
106                                 Log.w("network", "Response Set-Cookie headers is not a _SESSION one");
107                             }
108                         } else {
109                             Log.w("network", "Response has no Set-Cookie header");
110                         }
111                     }
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=\"([^\"]+)\">");
115                     String line;
116                     while ((line = reader.readLine()) != null) {
117                         //Log.d("dump", line);
118                         Matcher m = re.matcher(line);
119                         if (m.matches()) {
120                             token = m.group(1);
121                             Log.d("save-transaction", line);
122                             Log.d("save-transaction", "Token=" + token);
123                             return false;       // retry
124                         }
125                     }
126                     throw new IOException("Can't find _token string");
127                 } else {
128                     throw new IOException(String.format("Error response code %d", http.getResponseCode()));
129                 }
130             }
131         }
132     }
133
134     @Override
135     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
136         error = null;
137         try {
138             backend_url = Data.profile.get().getUrl();
139             ltr = ledgerTransactions[0];
140
141             int tried = 0;
142             while (!send_ok()) {
143                 try {
144                     tried++;
145                     if (tried >= 2)
146                         throw new IOException(String.format("aborting after %d tries", tried));
147                     sleep(100);
148                 }
149                 catch (InterruptedException e) {
150                     e.printStackTrace();
151                 }
152             }
153         }
154         catch (Exception e) {
155             e.printStackTrace();
156             error = e.getMessage();
157         }
158
159         return null;
160     }
161
162     @Override
163     protected void onPostExecute(Void aVoid) {
164         super.onPostExecute(aVoid);
165         task_callback.done(error);
166     }
167 }