]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java
replace dates in transaction list items with delimiters between items in different...
[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.Globals;
27 import net.ktnx.mobileledger.utils.NetworkUtil;
28 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
29
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.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 taskCallback;
46     protected String error;
47     private String token;
48     private String session;
49     private String backendUrl;
50     private LedgerTransaction ltr;
51
52     public SaveTransactionTask(TaskCallback callback) {
53         taskCallback = callback;
54     }
55     private boolean sendOK() throws IOException {
56         HttpURLConnection http = NetworkUtil.prepareConnection("add");
57         http.setRequestMethod("POST");
58         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
59         http.setRequestProperty("Accept", "*/*");
60         if ((session != null) && !session.isEmpty()) {
61             http.setRequestProperty("Cookie", String.format("_SESSION=%s", session));
62         }
63         http.setDoOutput(true);
64         http.setDoInput(true);
65
66         UrlEncodedFormData params = new UrlEncodedFormData();
67         params.addPair("_formid", "identify-add");
68         if (token != null) params.addPair("_token", token);
69         params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
70         params.addPair("description", ltr.getDescription());
71         for (LedgerTransactionAccount acc : ltr.getAccounts()) {
72             params.addPair("account", acc.getAccountName());
73             if (acc.isAmountSet())
74                 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
75             else params.addPair("amount", "");
76         }
77
78         String body = params.toString();
79         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
80
81         Log.d("network", "request header: " + http.getRequestProperties().toString());
82
83         try (OutputStream req = http.getOutputStream()) {
84             Log.d("network", "Request body: " + body);
85             req.write(body.getBytes("ASCII"));
86
87             try (InputStream resp = http.getInputStream()) {
88                 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
89                 if (http.getResponseCode() == 303) {
90                     // everything is fine
91                     return true;
92                 }
93                 else if (http.getResponseCode() == 200) {
94                     // get the new cookie
95                     {
96                         Pattern reSessionCookie = Pattern.compile("_SESSION=([^;]+);.*");
97
98                         Map<String, List<String>> header = http.getHeaderFields();
99                         List<String> cookieHeader = header.get("Set-Cookie");
100                         if (cookieHeader != null) {
101                             String cookie = cookieHeader.get(0);
102                             Matcher m = reSessionCookie.matcher(cookie);
103                             if (m.matches()) {
104                                 session = m.group(1);
105                                 Log.d("network", "new session is " + session);
106                             }
107                             else {
108                                 Log.d("network", "set-cookie: " + cookie);
109                                 Log.w("network",
110                                         "Response Set-Cookie headers is not a _SESSION one");
111                             }
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(
120                             "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
121                     String line;
122                     while ((line = reader.readLine()) != null) {
123                         //Log.d("dump", line);
124                         Matcher m = re.matcher(line);
125                         if (m.matches()) {
126                             token = m.group(1);
127                             Log.d("save-transaction", line);
128                             Log.d("save-transaction", "Token=" + token);
129                             return false;       // retry
130                         }
131                     }
132                     throw new IOException("Can't find _token string");
133                 }
134                 else {
135                     throw new IOException(
136                             String.format("Error response code %d", http.getResponseCode()));
137                 }
138             }
139         }
140     }
141
142     @Override
143     protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
144         error = null;
145         try {
146             backendUrl = Data.profile.get().getUrl();
147             ltr = ledgerTransactions[0];
148
149             int tried = 0;
150             while (!sendOK()) {
151                 try {
152                     tried++;
153                     if (tried >= 2)
154                         throw new IOException(String.format("aborting after %d tries", tried));
155                     sleep(100);
156                 }
157                 catch (InterruptedException e) {
158                     e.printStackTrace();
159                 }
160             }
161         }
162         catch (Exception e) {
163             e.printStackTrace();
164             error = e.getMessage();
165         }
166
167         return null;
168     }
169
170     @Override
171     protected void onPostExecute(Void aVoid) {
172         super.onPostExecute(aVoid);
173         taskCallback.done(error);
174     }
175 }