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