]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java
whitespace
[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 taskCallback;
45     private String token;
46     private String session;
47     private String backendUrl;
48     private LedgerTransaction ltr;
49     protected String error;
50
51     public SaveTransactionTask(TaskCallback callback) {
52         taskCallback = callback;
53     }
54     private boolean sendOK() throws IOException {
55         HttpURLConnection http = NetworkUtil.prepareConnection("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.addPair("_formid", "identify-add");
67         if (token != null) params.addPair("_token", token);
68         params.addPair("date", ltr.getDate());
69         params.addPair("description", ltr.getDescription());
70         for (LedgerTransactionAccount acc : ltr.getAccounts()) {
71             params.addPair("account", acc.getAccountName());
72             if (acc.isAmountSet())
73                 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
74             else params.addPair("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                 }
92                 else if (http.getResponseCode() == 200) {
93                     // get the new cookie
94                     {
95                         Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
96
97                         Map<String, List<String>> header = http.getHeaderFields();
98                         List<String> cookieHeader = header.get("Set-Cookie");
99                         if (cookieHeader != null) {
100                             String cookie = cookieHeader.get(0);
101                             Matcher m = reSessionCookie.matcher(cookie);
102                             if (m.matches()) {
103                                 session = m.group(1);
104                                 Log.d("network", "new session is " + session);
105                             }
106                             else {
107                                 Log.d("network", "set-cookie: " + cookie);
108                                 Log.w("network",
109                                         "Response Set-Cookie headers is not a _SESSION one");
110                             }
111                         }
112                         else {
113                             Log.w("network", "Response has no Set-Cookie header");
114                         }
115                     }
116                     // the token needs to be updated
117                     BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
118                     Pattern re = Pattern.compile(
119                             "<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                 }
133                 else {
134                     throw new IOException(
135                             String.format("Error response code %d", http.getResponseCode()));
136                 }
137             }
138         }
139     }
140
141     @Override
142     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
143         error = null;
144         try {
145             backendUrl = Data.profile.get().getUrl();
146             ltr = ledgerTransactions[0];
147
148             int tried = 0;
149             while (!sendOK()) {
150                 try {
151                     tried++;
152                     if (tried >= 2)
153                         throw new IOException(String.format("aborting after %d tries", tried));
154                     sleep(100);
155                 }
156                 catch (InterruptedException e) {
157                     e.printStackTrace();
158                 }
159             }
160         }
161         catch (Exception e) {
162             e.printStackTrace();
163             error = e.getMessage();
164         }
165
166         return null;
167     }
168
169     @Override
170     protected void onPostExecute(Void aVoid) {
171         super.onPostExecute(aVoid);
172         taskCallback.done(error);
173     }
174 }